0

I'm looking to set the datasource for a combobox. At the same time, i also want to set its display member and value member. Now, i have created a dictionary collection with key(long:value member) and value(string: display member).

Setting this dictionary to combo's data source throws the exception "Complex DataBinding accepts as a data source either an IList or an IListSource". Here is the code(see the data source assignment in the method):

    private IDictionary<long, string> Assessments = new Dictionary<long, string>();
    public void InitializeSelectedTemplates()
    {
        if (refreshParameters.SelectedPatient == null)
        {
            return;
        }

        vCheckListBoxToolStripItem1.CheckedComboBox.DataSource = Assessments;
        vCheckListBoxToolStripItem1.DisplayMember = "Value";
        vCheckListBoxToolStripItem1.CheckedComboBox.ValueMember = "Key";

        vCheckListBoxToolStripItem1.CheckedComboBox.Items.Clear();
        vCheckListBoxToolStripItem1.CheckedComboBox.Items.Add(ResAppConst.GetText("SelectAll"), 
        false);
     }

Note: If i make the following change to datasource assignment i get the exception 'Items collection cannot be modified when the DataSource property is set.'

vCheckListBoxToolStripItem1.CheckedComboBox.DataSource = new BindingSource(Assessments,null);

based on comments i changed the code as below and get the same error as originally reported:

vCheckListBoxToolStripItem1.CheckedComboBox.Items.Add(ResAppConst.GetText("SelectAll"), false);

    vCheckListBoxToolStripItem1.CheckedComboBox.DataSource = new BindingSource(Assessments,null);
    vCheckListBoxToolStripItem1.DisplayMember = "Value";
    vCheckListBoxToolStripItem1.CheckedComboBox.ValueMember = "Key";
sandy
  • 616
  • 2
  • 9
  • 20
  • doing vCheckListBoxToolStripItem1.CheckedComboBox.DataSource = new BindingSource(Assessments,null) throws the error 'Items collection cannot be modified when the DataSource property is set.' – sandy May 19 '21 at 12:51
  • Remove the `Clear()` and `Add(...)` calls. If you're binding you cant modify the collection (as the error says). If you need to add an item you need to first need to add it to the collection you're using to bind. Although I don't understand why the `Clear()` is even there. If you're trying to remove everything you just bound, why even bind? – Broots Waymb May 19 '21 at 12:54
  • Pls see my updates – sandy May 19 '21 at 13:05
  • You misunderstood my comment. You cannot have a call to `Items.Add(...)`. The collection you're using to bind is `Assessments`, so that is what you need to add to, then bind to everything in one go. You may also need to take some steps to handle this being called multiple times. I've definitely run into issues with trying to bind already bound controls. – Broots Waymb May 19 '21 at 13:12

0 Answers0