Binding to a C# ComboBox
It is possible to bind a field to a C# ComboBox such that the user can edit the value as well as choose a new one from a list.
Set DropDownType to DropDown to allow user input.
Populate your ComboBox by binding your DataTable of choices to it (or else add items manually):
myComboBox.DataSource = myDataChoicesTable;
myComboBox.DisplayMember = "field_text";
myComboBox.ValueMember = "field_text";
Then, bind a DataTable containing one row of data to the ComboBox:
myComboBox.DataBindings.Add("Text", myDataTable, "my_text");
An important note: Your myDataChoicesTable MUST contain as one of the options the value in myDataTable that you are initially using. Otherwise, the my_text value will be displayed, but the .Text value will not be correct. You will need to modify the sql that generates the myDataChoicesTable table and ensure the initial value is encluded. Don't know why this is necessary... seems like a bug to me- probably a 'feature' or else we're not supposed to be doing this.
Now, when the Combo's text is changed, the datasource needs to be updated manually, as it is not done by .NET. So, capture BOTH the TextChanged & SelectedValueChanged events, and add something like:
ComboBox cb = (ComboBox)sender;
string s = cb.DataBindings.BindingMemberInfo.BindingField.ToString();
DataTable dTable = (DataTable)cb.DataBindings.DataSource;
dTable.Rows[s] = cb.Text;
Finally, to get the value from the ComboBox, just call myComboBox.Text. Note that the SelectedValue and SelectedText properties will not "work" in this case, as you are binding to the Text property, not those other properties!
If you need to do some processing when the user changes the value of the ComboBox, you will need to put the action in BOTH the TextChanged and the SelectedValueChanged events of the ComboBox. This is because if the user types in a new value, the first event is fired. If they select a new value, the latter is fired. (Alternatively, put your logic in the LostFocus event, and just use the .Text property to get the value that was changed. (Though this will be called every time the user tabs through, even if they didn't change the value).
Lastly, in some rare cases, I needed to set BOTH the .Text property and .SelectedText property when setting the text automatically from code to get it to keep its value.
More problems: When the FIRST key is typed into the ComboBox, the TextChanged event fires, but the .Text property is NOT updated (retains old value). Solution would be to capture the Leave event and double check your data if you are doing processing on TextChanged.
Created By: amos 3/20/2006 12:12:59 AM
Updated: 6/2/2016 3:04:06 AM