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.. :)

No comments:

Post a Comment