Introduction
A common task for many developers is to insert an item at the beginning of a combobox
, such as 'Select an option', or something similar.
The problem with this option in Windows Forms is that you cannot simply add this new item to a bound combobox
. The new item needs to be added to the datasource
the combobox
is bound to.
I have created a helper method that accepts your existing datatable
, takes in a few arguments, and spits out datatable
with your newly added value. You then bind your combobox
to this new datatable
.
Let's look at some code to make this clearer...
Using the Code
public static DataTable GetComboBoxedDataTable
(DataTable oldDataTable, string valueColumn, string textColumn,
string topRowValue, string topRowText)
{
DataTable newDataTable = new DataTable();
newDataTable.Columns.Add(valueColumn);
newDataTable.Columns.Add(textColumn);
foreach (DataRow oldDR in oldDataTable.Rows)
{
DataRow newDR = newDataTable.NewRow();
newDR[0] = oldDR[valueColumn].ToString();
newDR[1] = oldDR[textColumn].ToString();
newDataTable.Rows.InsertAt(newDR, newDataTable.Rows.Count);
}
DataRow dr = newDataTable.NewRow();
dr[0] = topRowValue;
dr[1] = topRowText;
newDataTable.Rows.InsertAt(dr, 0);
return newDataTable;
}
This method takes 5 arguments:
oldDataTable
- This is your datatable
you have already bound to from your database.valueColumn
- This is the name of the column in your datatable
that you bind to the ValueMember
field of your combobox
.textColumn
- This is the name of the column in your datatable
that you bind to the DisplayMember
field of your combobox
.topRowValue
- This is the value of your 'Select' option you are adding to the combobox
.topRowText
- This is the displayed text of your 'Select' option you are adding to the combobox
.
The nice thing about this helper method is that it doesn't matter how many columns are in your original datatable
. It only strips out the columns you need for your combobox
as the standard combobox
only supports two columns.
To use the method, here is an example...
DataSet ds = GetDataSetFromMyDatabase();
comboBox.DataSource = GetComboBoxedDataTable(ds.Tables[0],
"ID", "EmployeeName", "0", "All Employees");
So there it is, a helper method to allow you to easily add a 'Select' option into a bound combobox
.
History
- 23rd October, 2009: Initial post