Click here to Skip to main content
Click here to Skip to main content

Windows DataGridColumns User Controls

, 29 Nov 2004
Rate this:
Please Sign up or sign in to vote.
How to build ComboBox, DateTimePicker and Button as User Controls for DataGridColumns for WinForms.

Sample Image


This article explains how to build some special user controls for DataGrid columns on a Windows application. The special controls are: DataGrid ComboBox, DateTimePicker and Button columns. In a DataGrid, a column style is an object that defines what the column looks and behaves like, including such things as color, font, and the presence of controls that will handle linked field in a database with the use of a ComboBox, a CheckBox and other controls. The .NET Framework includes two types of column-style classes by default: the DataGridTextBoxColumn and DataGridBoolColumn classes. A quantity of jobs you may want to achieve with the Windows Forms DataGrid control are, unexpectedly, more troublesome than you might expect. Principally, this is because the Windows Forms DataGrid control is column-based, rather than cell-based. As a result, to attain most tasks, you have to work with the columns, not the cells themselves. Hence the need to create our own set of DataGridColumnStyle objects that define custom column styles for the Windows Forms DataGrid control and add them to the GridColumnStylesCollection. Below is an explanation of how those three user controls might be useful:

DataGrid ComboBox Column Style

Suppose you have a database as shown below:


You have "StudentId", a foreign key to the "Id" field in "Student" table, and another field "BookName". Now, suppose you want to display the data of "Book" on a DataGrid, and don't want to display "StudentId" as integer. In addition, you need to display the name, but any editing would update the "StudentId" field. The first solution would be to create two DataTables with parent-child relation, and write many instructions to display the wanted fields correctly, and update the table as needed. This needs a lot of instructions and design. Another solution would be to use a combo box, with data source as the "Student" table, display member as "Name", and value member as "Id". And any edits would display the new name, but update the "StudentId" field. Using the DataGridComboBoxColumn class is easy to do that, and is added as a column to the DataGrid easily.

DataGrid DateTimePicker Column Style

Let's take the same database example as above. In the table "Book", there's a field "DateTime" with date information. Suppose you want to edit this field in the DataGrid directly. One way is to write the date, in the right format, in the text box column of the DataGrid. This could cause errors if you mistyped the date, or in a different format. Another solution would be to use a DateTimePicker control, and just choose the exact date from the control. Using the DataGridTimePickerColumn allows you to achieve that easily.

DataGrid Button Column Style

You are viewing all rows in the DataGrid. Now, suppose you want to delete a row from the DataSet. A simple way would be to click on a button on this row, and an event is fired to delete the row, then refresh the DataSet. This can be easily done using DataGridButtonColumn.

Using the code


This class builds the ComboBox column user control for DataGrids for Windows applications. It inherits from DataGridTextBoxColumn, since this is already an available control in the .NET Framework. What needs to be modified, depending on the application, is the Leave event.

private void comboBox_Leave(object sender, EventArgs e)
    DataRowView rowView = (DataRowView) this.comboBox.SelectedItem;
    string s=null;
    //in case the selected value is null.
            s = (string) rowView.Row[this.comboBox.DisplayMember];
    catch(Exception ex)

    SetColumnValueAtRow(this.cmanager, this.iCurrentRow, s);

    this.DataGridTableStyle.DataGrid.Scroll -= 
        new EventHandler(DataGrid_Scroll);            

Notice that the case where the selected value is null should be handled. Null values generate System.DBNull as output. This has to be converted to an empty string.

To use this class, simply add it to the project, construct an instance, and use its properties. This is a sample usage:

RamiSaad.DataGridComboBoxColumn comboboxColStyle = 
                          new RamiSaad.DataGridComboBoxColumn(); 
comboboxColStyle.ComboBox.DisplayMember = 
comboboxColStyle.ComboBox.ValueMember = 
comboboxColStyle.HeaderText =  "Student Id";
comboboxColStyle.MappingName =  _dataSet.Tables["Book"].Columns[i].ColumnName;

Note: You must set the properties and DataSource of the ComboBox property of the user control first before setting its header text and mapping name of the column style.


This class builds the DateTimePicker column user control for DataGrids for Windows applications. It inherits from DataGridTextBoxColumn, since this is already an available control in the .NET Framework.

This is a sample usage:

RamiSaad.DataGridTimePickerColumn timepickerColStyle = 
                     new RamiSaad.DataGridTimePickerColumn();
timepickerColStyle.HeaderText =  "Date";
timepickerColStyle.MappingName =  


This class builds the Button column user control for DataGrids for Windows application. It inherits from DataGridTextBoxColumn, since this is already an available control in the .NET Framework. To use this class, simply add it to the project, construct an instance, and use its properties.

Images of the button and button-pressed are attached with the class as well. You can add images to the solution, and choose "embedded resource" as build action in their properties. Then, in the class constructor, you must specify the location of the images in the assembly's resources:

    char[] c={','};
    System.IO.Stream strm = this.GetType().Assembly.GetManifestResourceStream(
    _button = new Bitmap(strm);
    strm = this.GetType().Assembly.GetManifestResourceStream(
    _buttonPressed = new Bitmap(strm);
catch(Exception ex)

This class uses handles, thus the constructor includes column number in its parameter. You must specify the DataGrid's column number in which the button control will be inserted:

RamiSaad.DataGridButtonColumn buttonColStyle = 
  new RamiSaad.DataGridButtonColumn(i); //pass the column#

A button click event argument class is inserted in the same control's class. This is useful to manage the messages or actions when the button is clicked:

public delegate void DataGridCellButtonClickEventHandler(object sender, 
                                    DataGridCellButtonClickEventArgs e);

public class DataGridCellButtonClickEventArgs : EventArgs
    private int _row;
    private int _col;

    public DataGridCellButtonClickEventArgs(int row, int col)
        _row = row;
        _col = col;

    public int RowIndex    {get{return _row;}}
    public int ColIndex    {get{return _col;}}

Note: You must define the button click event handler DataGridCellButtonClickEventHandler. This will be called from the form itself which calls the DataGrid.

Here is a sample on how to use this class from the DataGrid's form:

    buttonColStyle = new RamiSaad.DataGridButtonColumn(i); //pass the column#
    buttonColStyle.HeaderText =  "Delete";
    buttonColStyle.MappingName =  _dataSet.Tables["Book"].Columns[i].ColumnName;

    //hookup our cellbutton handler...
    buttonColStyle.CellButtonClicked += 
    new RamiSaad.DataGridCellButtonClickEventHandler(HandleCellButtonClick);


    //hook the mouse handlers
    dataGrid1.MouseDown += new MouseEventHandler(buttonColStyle.HandleMouseDown);
    dataGrid1.MouseUp += new MouseEventHandler(buttonColStyle.HandleMouseUp);
// handler for a click on one of the gridcell buttons
private void HandleCellButtonClick(object sender, DataGridCellButtonClickEventArgs e)
    MessageBox.Show("row " + e.RowIndex.ToString() +  " will be deleted.");

Note: The handler for a button click is inserted in the DataGrid's form itself. Also, you must hook the mouse handlers to the button column style.

That's all. The user controls' classes are easy to use, as explained above. Hopefully, more user controls will be added later. Please let me know of any feedback or comment on this article or code.

Points of Interest

.NET Framework v2.0 already has these extra user controls available. When designing a DataSet, you can create many types of column styles, including those mentioned in this article. But still, sometimes it is very hard to migrate from Framework 1.1 to Framework 2.0, and thus the need to create user controls.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Rami Saad
Web Developer
Ireland Ireland
Expert in Microsoft technologies.
MCP in developing windows applications. Worked in hardware/software development, system design/integration.
Currently working as Partner Technical Specialist.

Comments and Discussions

GeneraltableStyle problem PinmemberJML_4-Apr-11 23:48 
GeneralExcelent. I Need help PinmemberMember 548844731-Mar-09 13:35 
QuestionProblem with ComboBox PinmemberJames24322228-Jan-09 4:10 
QuestionProblem with DateTimePicker PinmemberJames24322227-Jan-09 11:06 
Generalsuggested books Pinmembermohitpaliwal16-Oct-08 21:59 
Generalbutton in datagrid Pinmembersharma sanjeev18-Jun-07 20:50 
Generalrows with differen controls PinmemberGiorgi Dalakishvili5-Apr-07 10:00 
GeneralCombo Box Pinmembermykosher10-Oct-06 4:07 
Questiondatagridcomboboxcolumn in master-detail form PinmemberNaman Patel11-Aug-06 2:16 
Questionwhy datagridbutton can't use windows button contrl? Pinmemberbeelzebub10-Jun-06 20:33 
QuestionHow to fix recursive firing of DataGrid Button Click events Pinmembernaruji5-Jun-06 4:02 
Generalcompact framework Pinmembercsharppointer19-Apr-06 5:42 
GeneralRe: compact framework Pinmemberjrb430@gmail.com25-Jul-07 16:09 
GeneralDataGridComboBoxColumn, DataGridComboBoxColumn PinmemberL C D8-Mar-06 16:53 
GeneralSystem.NullReferenceException Pinmemberhadhmy17-Jan-06 2:42 
GeneralDoubt Regarding datagrid and dataview PinmemberDurga Venkateswara Rao16-Jan-06 1:26 
QuestionWindows DataGridColumns User Controls Pinmemberdbn_0110-Jan-06 18:58 
GeneralWindows DataGridColumns User Controls Pinmemberdbn_0110-Jan-06 18:56 
GeneralComboBox Column of Datagrid PinmemberHemaRawat27-Dec-05 23:31 
GeneralRe: ComboBox Column of Datagrid Pinmemberdeveloper20097-Dec-06 20:24 
Generaldifferent button to each row Pinmemberkirkegor15-Nov-05 22:08 
Generalerror new row with DataGridTimePickerColumn Pinmemberdaouadji6-Oct-05 4:21 
GeneralRe: error new row with DataGridTimePickerColumn PinmemberZuoliu Ding2-Nov-05 12:13 
GeneralRe: error new row with DataGridTimePickerColumn Pinmemberdaouadji23-Dec-05 8:20 
Questionhow to manually set a value from code Pinmemberir_fuel22-Sep-05 10:51 
Generalmaybe fix for mousescroll crash Pinmemberir_fuel22-Sep-05 7:50 
GeneralGet cell value PinmemberLimit_isNo_Limit27-Aug-05 2:10 
GeneralRequired Field In datagrid Pinmembermutahar21@hotmail.com20-Aug-05 1:04 
GeneralTab key can not stop on Datetimepicker column Pinsusshtphuoc197825-Jul-05 18:25 
GeneralRe: Tab key can not stop on Datetimepicker column PinmemberVlad Stanciu11-Nov-05 1:19 
GeneralLoosing Focus from Combobox column when we keep press tab PinmemberAnji Reddy K5-Jul-05 20:13 
Generalrow color Pinmembertvprithiv26-Jun-05 23:40 
GeneralPAINT EVENT Pinmemberrodriguesd6-Apr-05 22:48 
GeneralFixed keyboard navigation error PinmemberMikkel Rostock27-Mar-05 5:09 
GeneralRe: Fixed keyboard navigation error PinmemberMark Harmon13-Sep-05 11:31 
GeneralSetColumnValueAtRow() error PinmemberStephenKearney15-Mar-05 16:15 
GeneralRe: SetColumnValueAtRow() error PinmemberMark Harmon13-Sep-05 11:23 
QuestionRe: SetColumnValueAtRow() error Pinmemberlaxhy18-Mar-06 3:24 
GeneralDataGrid Relations PinmemberChiara Zachary3-Mar-05 4:11 
GeneralRe: DataGrid Relations PinmemberRami Saad8-Mar-05 15:10 
Generalnamespace PinmemberChiara Zachary23-Feb-05 7:19 
I copied your Form1 & DataGridButtonControl into my project named "HAISurveyMDI". I alter the namespace from "DataGridUserControls" to "HAISurveyMDI" & ran the project. This causes a null value when streaming the bitmap i.e. "System.IO.Stream strm = this.GetType().Assembly.GetManifestResourceStream(this.GetType().Assembly.ToString().Split(c,10)[0]+".button.bmp");". I'm confused. Can you help???
GeneralRe: namespace PinmemberRami Saad23-Feb-05 11:13 
GeneralRe: namespace PinmemberChiara Zachary23-Feb-05 23:58 
GeneralError on adding new row Pinmemberlagor23-Feb-05 4:21 
GeneralRe: Error on adding new row PinmemberRami Saad28-Feb-05 12:32 
GeneralError when not selecting a value from the Combobox Pinmemberlud1233-Feb-05 21:56 
GeneralRe: Error when not selecting a value from the Combobox PinmemberRami Saad4-Feb-05 4:33 
GeneralRe: Error when not selecting a value from the Combobox Pinmemberlud1234-Feb-05 21:28 
GeneralRe: Error when not selecting a value from the Combobox PinmemberRami Saad5-Feb-05 1:33 
GeneralRe: Error when not selecting a value from the Combobox Pinmemberlud1235-Feb-05 22:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 30 Nov 2004
Article Copyright 2004 by Rami Saad
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid