I have a combo box with a DataSource based on an array of objects, and the Value
property is bound to a property on a model repository:
DataSource = someArray;
ValueMember = "ArrayValue";
DisplayMember = "Name";
DataBindings.Add("Value", repository, "RepositoryValue");
DataBindings["Value"].DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;
In some scenarios the user changes the selected item in the combo box and it is reflected in repository.RepositoryValue
, and sometimes we pull data from a file or database and directly populate repository.RepositoryValue
which is then automatically reflected in the combox box. Occassionally it is possible for the file or database to contain an invalid value (something not included in someArray
), and we would like to detect that scenario and force the combo box to select the first item in the list or reject the change entirely. Is this possible, and how should w开发者_Go百科e go about doing it?
You can use Format event of Binding to handle it.
Binding SelectedValueBinding = new Binding("SelectedValue", repository, "RepositoryValue", true, DataSourceUpdateMode.OnPropertyChanged);
SelectedValueBinding.Format += new ConvertEventHandler(SelectedValueBinding_Format);
myComboBox.DataBindings.Add(SelectedValueBinding);
void SelectedValueBinding_Format(object sender, ConvertEventArgs e)
{
// if e.Value is Invalid
// myComboBox.SelectedValue = "Default Value";
}
Check more on:
How does one databind a custom type to TextBox.Text?
精彩评论