1
votes

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!

2

2 Answers

1
votes

If this was a web form, I might suggest having ComboBox2 as two separate ComboBoxes and hide/show the one you need. Although I appreciate this isn't quite so easy for a WinForm project, unless you're using a flowing layout?

You could add a function to return your data source, based on your enumeration type... I don't think you need to re-set your DisplayMember and ValueMember properties after calling Clear() (but I may be wrong).

Other than that, I don't think you can simplify it much more. Although I'd be happy to hear if someone has a better solution :)

0
votes

You don't need to bind the ComboBoxes to a new instance of BindingSource.

Bind your ComboBoxes to their respective BindingSources. This can be done either through the Windows Forms Designer, or manually in your own code. Make sure to keep a reference to the BindingSources if you do it in your code. If you use the Designer, then a member is added for you to your Form class.

Then when you want to display a different set of values, all you need to do is change the DataSource on the BindingSources, and the ComboBoxes will update accordingly.

Cheers