Introduction
This is a descendant from DataGridColumnStyle
and is used to have a ComboBox
in a DataGrid
column. It is based on an article by Sudhakar Jalli but I found the code not working. I repaired the code and cleaned it up a little.
The DataGridComboBoxColumn
class makes it possible to have a ComboBox
instead of the default text or checkbox. It took me quite a while to figure it out (even with the help of the article by Sudhakar Jalli). Using it is straightforward.
Using the code
First create a new DataGridTableStyle
and make sure the mapping is set to the name of the table in the DataSource
where the columns will belong to.
DataGridTableStyle ts=new DataGridTableStyle();
ts.MappingName="Columns";
Then, create the DataTable
with the lookup values. This could of course come from the database (And it should BTW)
DataTable AccessDataTypes = new DataTable();
AccessDataTypes.Columns.Add(new DataColumn("Number", typeof(int)));
AccessDataTypes.Columns.Add(new DataColumn("Name", typeof(string)));
AccessDataTypes.Rows.Add(new object[] {3, "Numeric"});
AccessDataTypes.Rows.Add(new object[] {130, "Text"});
Create the DataGridComboBoxColumn
and add it to the GridColumnStyles
. The first argument (Type
) is used for the column caption and the mapping. (Could be changed after creating). The second argument (AccessDataTypes
) is the DataTable
to use for translation. Name
and Number
are the column names to use from the table and theGrid
is the DataGrid
where this column will belong to. Be sure to provide the NullText
; if you don't it will throw an exception if you try to add a row to the DataGrid
.
DataGridComboBoxColumn c1=new DataGridComboBoxColumn("Type",
AccessDataTypes, "Name", "Number", theGrid);
c1.NullText="3";
ts.GridColumnStyles.Add(c1);
Finally add the newly created TableStyle
to the TableStyles
array of the DataGrid
.
theGrid.TableStyles.Add(ts);
Enjoy the improved DataGrid
and be sure to send in your own DataGrid
columns!