13 June 2014

Auto Complete TextBox in Window Form C#

Hi All,

Let see how to create the AutoComplete TextBox in window form.
You might be aware of Auto Complete in web page using the Ajax and JQuery plugins or using the asp.net ajax toolkit.

But when it comes to the Auto Complete TextBox in Window Form some people find it difficult.

I am gonna demonstrate you Auto Complete Textbox for months Jan - Dec.

Download Sample
  • Open Visual Studio and create a Window Form application. 
  • It will add a blank default Window Form for you.
  • Drag a label name it Months and a Input TexBox for Auto Complete Months.

  • Double Click form to open Form_Load event. and create AutoCompleteStringCollection class object.
  • Add you indented string item in object in this case months name string array.
        private void Form1_Load(object sender, EventArgs e)
        {            
            // Create the list to use as the custom source.  
            var source = new AutoCompleteStringCollection();            
            source.AddRange(new string[]
                    {
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December"
                    });
            
            // attched it with the created text box.
            textBox1.AutoCompleteCustomSource = source;
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        }

  • Bind the AutoCompleteStringCollection with textBox1.

and you are done.  Now when you run the form and just type only one character "j" it will show the months starting from "j".

Happy knowledge sharing.. ☺

26 March 2014

Parent Div height zero(0) even child div has content

Hi,

Let see what happened when we float the child div to Left or Right. Parent Div shows the height as 0.

<html>
  <head>
    <style>
      #parent
      {
        width:100%;
        height:auto;
      }
      #child
      {
        float:right;
        width:25%;
        height:auto;
        border:1px solid black;
        margin:10px;
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="child">
        this is the content inside the child
      </div>
    </div>
  </body>
</html>

It shows the result as -


Notice child div has content so it has the height but if child div has the height why parent div showing height as zero(0)??

Its because of you set the
float:right; 
on child div which make it position:absolute and thats why parent div height is zero.  To correct is you just need to set the overflow:hidden on parent div.

modified the css part as below -
      #parent
      {
        width:100%;
        height:auto;
        overflow:hidden;
      }
And you are good to go you will get the correct result as -

Happy Blogging and Sharing.. ☺☻

25 February 2014

Read-Write Excel file in Java

Hi All,

Lets see you can read/write the data from/to Excel worksheet(.xls file) .  Its very useful when you provide the option to export and import the data in you web page.



package myExcel;
import java.io.File;
import java.io.FileInputStream;

import  org.apache.poi.hssf.usermodel.HSSFSheet;  
import  org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import  org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;

public class ReadExcel {
  public static void main(String[] args) {
    try
    {
      File f = new File("C:\\Users\\dsharma\\Desktop\\Excel.xls");
      FileInputStream fin = new FileInputStream(f);
      HSSFWorkbook workbook = new HSSFWorkbook(fin);
      HSSFSheet tempSheet;
      HSSFRow tempRow;
      HSSFCell tempCell;
      for (int i = 0; i < workbook.getNumberOfSheets() ; i++) {
        tempSheet = workbook.getSheetAt(i);
        System.out.println("Sheet - \""+tempSheet.getSheetName()+"\"");
        /*
         *  remember getLastRowNum() returns the 0 based index
         *  so we have to use ( "<=" )
         *  
         *  in for loop  [ j <=  tempSheet.getLastRowNum() ]
         */                 
        for (int j = 0; j <= tempSheet.getLastRowNum() ; j++) {
          tempRow = tempSheet.getRow(j);      
          if(tempRow!=null)
          {
            for (int j2 = 0; j2 <tempRow.getLastCellNum(); j2++) {
              tempCell = tempRow.getCell(j2);
              System.out.printf("%-15s|",tempCell);
            }
          }          
          System.out.println("");
        }
        System.out.println("\n\n");
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }    
  }
}

This will read you excel file specified at line number 15. and will print the data in all the sheets inside your excel workbook.

And Lets see how can you create and write excel file(.xls) from your Java Code.
package myExcel;

import java.io.File;
import java.io.FileOutputStream;

import  org.apache.poi.hssf.usermodel.HSSFSheet;  
import  org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import  org.apache.poi.hssf.usermodel.HSSFRow;

public class WriteExcel {
  public static void main(String[] args) {
    try{          
      HSSFWorkbook workbook = new HSSFWorkbook();      
      HSSFSheet tempSheet = workbook.createSheet("Created Sheet");
      
      //Create first row reference from the sheet "tempSheet"
      HSSFRow tempRow = tempSheet.createRow(0);
      
      //add the 3 column and value in first row
      tempRow.createCell(0).setCellValue("Roll No.");
      tempRow.createCell(1).setCellValue("Name");
      tempRow.createCell(2).setCellValue("Passed?");
      
      //adding 5 students details
      for (int i = 0; i < 5; i++) {
        //create second row. as first is header
        tempRow = tempSheet.createRow(i+1);
        
        //add three columns value
        tempRow.createCell(0).setCellValue(i+1);
        tempRow.createCell(1).setCellValue("Student "+(i+1));
        tempRow.createCell(2).setCellValue(i%2==1);
      }
        
      //outputstream object of the file to be created
      File f = new File("C:\\Users\\dsharma\\Desktop\\New_Excel.xls");    
      FileOutputStream fout = new FileOutputStream(f);
      workbook.write(fout);
    }
    catch(Exception ex){
      ex.printStackTrace();
    }
  }
}

You can see for both read-write we need few new reference, yes we need a library file. Called "Apache POI library",  don't worry you can download the that jar file from the below links.
Download POI

So this is the basic to read and write the Excel file in Java.  Now if you find its typical to implement it in you JSP-Servlet webproject?? get the below sample project(Eclipse Project.  jdk1.7  used).  Don't worry for the library for JSP project, I have included all the jar file inside the project.

Download Eclipse Project(.ZIP)

Happy Coding and Sharing.. :)

25 January 2014

Convert DataGridView column to Combo Box

Hi Friends,

Sometime if you work in windows form application in C# or using VB,  you may face a problem where you want to put a combo on a field in grid view for a column from the data source table.

Consider a gridview displaying the information of the student  or employee then for the Gender field you may want a Combo Box having the two value Male and Female,  so that for the new record user no need to type the gender value MALE or FEMALE he will select the value from the Combo Box.


So you want to convert plain text column Combo Box. You can download the above sample from the given download link.  Download Sample.

In Form_Load event code the below part.  just copy-paste the below code.

DataTable dt = new DataTable();

private void getDataSource()
{
 dt.Columns.Add("Name");
 dt.Columns.Add("Last");
 dt.Columns.Add("Gender");

 dt.Rows.Add("Rohit", "Sharma", "Male");
 dt.Rows.Add("Saurabh", "Singh", "Male");
 dt.Rows.Add("Gurpreet", "Kaur", "Female");        
}

private void Form1_Load(object sender, EventArgs e)
{
    // just fill the dummy record in datatable dt
    getDataSource();

    // table dt has three column index 0,1,2
    dataGridView1.DataSource = dt;

    // create Combo Box Cell
    DataGridViewComboBoxCell bc = new DataGridViewComboBoxCell();               
 
    //if want to add the fix value in ComboBox Male and Female
    bc.Items.AddRange("Male","Female");
 
    /*  if you want to get the existing value in gender column 
     * and display them in ComboBox
     */
     // var ss = dt.AsEnumerable()
     //           .Select(_ => _.Field<string>("gender")).
     //           .Distinct();
     // bc.Items.AddRange(ss.ToArray());

    /* add one more column at index 3 as ComboBox for the value
     * in index-2 column "Gender"    
     */
    DataGridViewColumn cc = new DataGridViewColumn(bc);
    dataGridView1.Columns.Add(cc);
    dataGridView1.Columns[3].HeaderText = dataGridView1.Columns[2].HeaderText;
    

    /* hide the plain value for gender mean index-2 column as we
     * have index-3 column as combobox for gender
     */
    dataGridView1.Columns[2].Visible = false;       

    // set the gender value in combobox
    foreach (DataGridViewRow item in dataGridView1.Rows)
    {
       item.Cells[3].Value = item.Cells[2].Value;
    }    
}

Happy Code sharing and Blogging.. :)

22 January 2014

DataGridView not showing the DataSource (List, Array) in Grid

Hi Friends,

Sometime we bind the datasource with DataGridView object but still it doesn't show the data in grid view.

Consider we have a class Employee as

 class Employee
 {
     public string fname;
     public string sname;

     public Employee(string f, string s)
     {
         fname = f;
         sname = s;
     }
 }

and we bind List/Array of the Employee class as the datasource of the DataGridView in window form as below -

public partial class Form1 : Form
{
    List<Employee> lst = new List<Employee>();    
    
    public Form1()
    {
        InitializeComponent();

        lst.Add(new Employee("deepak1", "sharma"));
        lst.Add(new Employee("deepak2", "sharma"));
        lst.Add(new Employee("deepak3", "sharma"));                
        
        dataGridView1.DataSource = lst;
        dataGridView1.Refresh();        
    }

}

but when we open the form we are not able to see the data in datagridview.

The main reason is we don't have get set properties in Employee class.  Even the fname and sname are public but still we have to define the properties for the attribute we want to show.

You just need to modify two line in your Employee class.



 class Employee
 {
     public string fname; 
     public string sname; 
    
     public string fname { get; set; }
     public string sname { get; set; }
    
     public Employee(string f, string s)
     {
         fname = f;
         sname = s;
     }
 }

Now if you run the above code it will display the records in DataGridView. :)

Happy Code Sharing and Blogging.. :)