65.9K
CodeProject is changing. Read more.
Home

How To Add Custom ComboBox Column to DataGridView in Windows Forms

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (4 votes)

Oct 14, 2014

CPOL
viewsIcon

10171

How to add a custom ComboBox column to DataGridView in Windows forms

In this post, we will see how we can 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!