October 14, 2014 by Nitesh

How To Add Custom ComboBox Column to DataGridView in Windows Forms

Friends,

In this post we will see how can we add a custom ComboBox column to DataGridView in Windows forms. This scenario generally comes when we need to edit a row in the DataGridView and allow users to select value for a cell from a predefined set of values. This post will help you achieve the same.

This post assumes that the name of the DataGridView is gridRecords and GetDataFromDatabase() function returns a DataTable with data to be assigned to the DataGridView.

    private void LoadGrid()
    {
       gridRecords.Columns.Clear();
       gridRecords.DataSource = GetDataFromDatabase();
       if(gridRecords.Columns.Count > 0) // Add Checkbox column only when records are present.
          AddComboBoxColumn();
    }
    private void AddComboBoxColumn()
    {
       DataGridViewComboBoxColumn dgcm = new DataGridViewComboBoxColumn();
       dgcm.HeaderText = "Employee";
       DataTable dt = new DataTable();
       dt.Columns.Add("ID");
       dt.Columns.Add("Name");
       for(int i=1;i<5;i++)
       {
           DataRow dr = dt.NewRow();
           dr["ID"] = i;
           dr["Name"] = "Employee " + i;
           dt.Rows.Add(dr);
       }
       dgcm.ValueMember = "ID";
       dgcm.DisplayMember = "Name";

       dgcm.DataSource = dt;
            
       gridRecords.Columns.Add(dgcm);
    }

In the above code, we set the DataSource of DataGridView control with the datatable. Once set, we add a new column named “Employee” to the DataGridView at the end of the grid.

Hope you like this! Keep learning and sharing! Cheers!

#.Net#Utilities#Winforms

Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup