I have a Winforms app with a BindingSource component and its DataSource is set to a DataSource that I created for a custom data object. Also on the form are several controls that are bound to various properties of the object exposed through the BindingSource. Many of these controls are comboboxes and will display values with a backing enum so I'm setting the DataSource for these controls like this:
comboBox1.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.EnumValues)), null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
This is all working well enough but I have two comboboxes which I need to be able to change at runtime to display other values (with a different back enum). In these two cases, I'm creating the initial bindings and datasource in code like this:
comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName1", true));
comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.FirstSetOfEnumValues)), null);
comboBox2.DisplayMember = "Value";
comboBox2.ValueMember = "Key";
...and then when I need comboBox2 to bind to and display different values, I do this:
comboBox2.DataBindings.Clear();
comboBox2.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "PropertyName2", true));
comboBox2.DataSource = null;
comboBox2.DataSource = new BindingSource(Utility.ToList(typeof(DataObject.SecondSetOfEnumValues)), null);
comboBox2.DisplayMember = "Value";
comboBox2.ValueMember = "Key";
As best I can tell, this is working properly, but it's ugly and there has got to be a much better way to do this, right? If you know what it is, I'd love to hear it! Thanks very much!