How To Add Custom ComboBox Column to DataGridView in Windows Forms

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.

  1. private void LoadGrid()    
  2. {    
  3. gridRecords.Columns.Clear();    
  4. gridRecords.DataSource = GetDataFromDatabase();    
  5. if(gridRecords.Columns.Count > 0) // Add Checkbox column only when records are present.    
  6. AddComboBoxColumn();    
  7. }    
  8. private void AddComboBoxColumn()    
  9. {    
  10. DataGridViewComboBoxColumn dgcm = new DataGridViewComboBoxColumn();    
  11. dgcm.HeaderText = "Employee";    
  12. DataTable dt = new DataTable();    
  13. dt.Columns.Add("ID");    
  14. dt.Columns.Add("Name");    
  15. for(int i=1;i<5;i++)    
  16. {    
  17. DataRow dr = dt.NewRow();    
  18. dr["ID"] = i;    
  19. dr["Name"] = "Employee " + i;    
  20. dt.Rows.Add(dr);    
  21. }    
  22. dgcm.ValueMember = "ID";    
  23. dgcm.DisplayMember = "Name";    
  24. dgcm.DataSource = dt;    
  25. gridRecords.Columns.Add(dgcm);    
  26. }   

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!


Similar Articles
Rebin Infotech
Think. Innovate. Grow.