MartinLarge
asked on
Data bound ComboBox
I have a combo box on a pocket pc form with the data source set to a DataTable and the ValueMember set to an ID field and the DisplayMember set to a Description field.
To get a blank entry at the top of the combo box I add a row to the beginning of the DataTable with an ID of 0 and a description of spaces.
Sometimes i need to select a specific value when loading the combo box so it displays the correct item on entry. I do this as follows:
this.combobox.SelectedValu e = ID (where ID > 0)
If there are 2 or more rows in the DataTable (before i add a blank one) it works fine.
However, if there is only 1 row in the DataTable an unspecified exception is thrown.
Any idea why, or how this can be avoided???
To get a blank entry at the top of the combo box I add a row to the beginning of the DataTable with an ID of 0 and a description of spaces.
Sometimes i need to select a specific value when loading the combo box so it displays the correct item on entry. I do this as follows:
this.combobox.SelectedValu
If there are 2 or more rows in the DataTable (before i add a blank one) it works fine.
However, if there is only 1 row in the DataTable an unspecified exception is thrown.
Any idea why, or how this can be avoided???
ASKER
I have an Id with a value of 8 when there are only 3 rows in the table and it still works. It doesn't work if there is only 1 row in the original table.
What you suggested would be OK if using SelectedIndex but i'm using SelectedValue from a datasource.
What you suggested would be OK if using SelectedIndex but i'm using SelectedValue from a datasource.
You have right (it was SelectedIndex), then you must verify that exists an item with the ValueMember with your ID:
if (combobox.Items.Contains(I D))
combobox.SelectedValue = ID;
if (combobox.Items.Contains(I
combobox.SelectedValue = ID;
ASKER
The Id does exist within the DataTable.
If the DataTable has 2 rows the combo box works fine and selects the correct id.
If i remove the row which does not match the id it crashes.
I think there is a problem with adding the blank datarow to the DataTable.
When i don't do this it works fine.
If the DataTable has 2 rows the combo box works fine and selects the correct id.
If i remove the row which does not match the id it crashes.
I think there is a problem with adding the blank datarow to the DataTable.
When i don't do this it works fine.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
if (combobox.Items.Count > ID)
combobox.SelectedValue = ID;