Friends,
In this article we will see how to add a custom ComboBox column to DataGridView in Windows Forms. This scenario generally occurs when we need to edit a row in the DataGridView and allow users to select a value for a cell from a predefined set of values. This article will help you do that.
This article assumes that the name of the DataGridView is gridRecords and the 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)
- 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 code above, we set the DataSource of the DataGridView control with the datatable. Once set, we add a new column named “Employee” to the DataGridView at the end of the grid.
I hope you like this! Keep learning and sharing! Cheers!