Following is my code which is binding a List() to a ComboBox control. I tried to add few items to the CombBox control using Insert() method which is not allowed as it has been assigned to a datasource. So, how can I get the datasouce back to a new variable (say, var colours2) from cmbColour.DataSource which is returning an object. Thanx !
var colours= new Dictionary<string, string>
{
{"1x","Green"},
{"2x","Red"},
{"3y","Blue"},
{"4y","Black"}
}.ToList();
cmbColour.ValueMember = "Key";
cmbColour.DisplayMember = "Value";
cmbColour.DataSource = colours;
var colours2 = //how can I get the DataSource back
The following code will return a new dictionary containing the same data you bound to the combo box.
The property
DataSourcewill return the same instance you assigned but because it is typedObjectyou have to cast it back to the actual type before you can access any members.But why don’t you just keep the original dictionary? And it is definitely supported to modify a list bound to a data source – that is the whole point of data binding.
I guess my answer does not really solve your actual problem, only what you think what your problem is. Maybe you can give some additional information about what you are trying to achieve and I or someone else will be able to help you with your underlying problem.
UPDATE
This should work for your scenario – I stick with the user example.
And the code for the form.
Note the usage of
BindingList<T>– this will notify the combo box about any changes to the list. A simpleList<T>would also work but then you have to explicitly tell the combo box to refresh the data binding.