Add databound ComboBoxes to the WinForms DataGrid using derived column styles

This page includes a VB.NET sample and a C# sample that displays a DataGrid containing two regular textbox columns and 2 columns containing databound ComboBoxes.

To use databound comboboxes in the datagrid the sample derives a new datagrid column style from the DataGridTextBoxColumn class and adds overrides for the SetColumnValueAtRow, GetColumnValueAtRow, Edit, Commit and ConcedeFocus methods. This is performed in the DataGridComboBoxColumn class.

The Edit event is raised when the user sets the focus to the cell containing the combobox. In this event the dimensions of the combobox are set and an event handler is assigned to handle scrolling of the combobox.

When a value is changed in the combobox and you leave the grid cell the new value must update the corresponding value in the bound data source. This requires tracking when the user starts to edit the combobox value and then commiting the changes to the data source. Hence the override to the Edit and Commit events.

A second NoKeyUpCombo class derives a new ComboBox whose WndProc method is overridden. This is required to address issues when TABbing through the grid so as not to leave focus on the combobox. It is this derived combobox that is added to the datagrid.

While there are a number of methods that you must think about, the code is not complicated.

The samples use fake databases and tables. But the concepts are there. You can easily create a SQL Server or MS Access database modelled after the tables referenced in the code. Or you can change the code to use your own real databases. You will also need to modify the database connection string.

Download the VB.NET source code

Download the C# source code




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page