Unselect Databound Combobox Winforms .NET
- by joedotnot
The problem: combobox is databound to a DataView, first item in the dataview is DataRowView whose fields are DBNull.Value; Combo DropdownStyle = ComboBoxStyle.DropDownList
Loads fine, displays fine, selects fine, problem is to Unselect via code. Setting the SelectedIndex to 0 throws an exception. (Setting to -1 is a no-no as per msdn doco that says dont set SelectedIndex=-1 if databound)
So how to unselect without throwing an exception ?
For now i wrapped it into a try/catch to just ignore the error!
EDIT: As asked by Hubeza, i worked on sample code to post. Did a stripped down version of the original code in C# (original is in VB.NET) and could NOT reproduce it either. Converted to VB.NET and could NOT reproduce it either ! In other words, SelectedIndex = 0 does work in the stripped down version!
Currently further investigating what else could be wrong with the original code.
EDIT2: Case Closed. Call me a stupid fool if you like, and apologies for wasting anyone's time - The error was originating from MyComboBox_SelectedIndexChanged event, which i neglected to check !
May as well post the sample in case anyone finds useful.
private void LoadComboMethod() {
DataTable dtFruit = new DataTable("FruitTable");
//define columns
DataColumn colID = new DataColumn();
colID.DataType = typeof(Int32); //VB.NET GetType(Int32)
colID.ColumnName = "ID";
DataColumn colDesc = new DataColumn();
colDesc.DataType = typeof(String);
colDesc.ColumnName = "Description";
//add columns to table
dtFruit.Columns.AddRange(new DataColumn[] { colID, colDesc });
//add rows
DataRow row = dtFruit.NewRow();
row[colID] = 1; row[colDesc] = "Apples";
dtFruit.Rows.Add(row);
row = dtFruit.NewRow();
row[colID] = 1; row[colDesc] = "Bananas";
dtFruit.Rows.Add(row);
row = dtFruit.NewRow();
row[colID] = 1; row[colDesc] = "Oranges";
dtFruit.Rows.Add(row);
//add extra blank row.
DataRowView drv = dtFruit.DefaultView.AddNew();
drv.EndEdit();
//Bind combo box
DataView dv = new DataView(dtFruit);
dv.Sort = "ID ASC"; //ensure blank item on top
cboFruit.DataSource = dv;
cboFruit.DisplayMember = "Description";
cboFruit.ValueMember = "ID";
}
private void UnselectComboMethod() {
if (cboFruit.SelectedIndex > 0)
{
cboFruit.SelectedIndex = 0;
}
else
{
MessageBox.Show("no fruit selected");
}
}