0
votes

Running a project with linq to sql model, and binding my combos to bindingsource controls, I have two comboBoxes, first shows a table which shows database tables names (ID, TableName) and the second should be bound to the selected table in the first combo, I tried this code:

        private void ComboBox1_TextChanged(object sender, EventArgs e)
    {
        if (ComboBox1.Text == "Customers")
        {
            var qry = (from u in dc.Customers
                       select u).ToList();
            comboBox2.ValueMember = "CustomerID";
            comboBox2.DisplayMember = "CompanyName";
            comboBox2.DataSource = qry;
        }
        if (ComboBox1.Text == "Suppliers")
        {
            var qry = (from u in dc.Suppliers
                       select u).ToList();
            comboBox2.ValueMember = "SupplierID";
            comboBox2.DisplayMember = "CompanyName";
            comboBox2.DataSource = qry;
        }
    }

With the code above I can show the first combo items, I can show also the second combo items by default, but when I change the first combo content I get error at comboBox2.ValueMember = "SupplierID"; : System.ArgumentException was unhandled Message=Link to the new Value member impossible. Please how can I reset the combobox2.ValueMember to the new field name?

2
Please tell me the fields inside dc.Suppliers the error is throw n because Suppliers does not have SupplierID in itHatSoft
Supplier have SupplierID field, you can verify that on Northwind database sample.Sami-L

2 Answers

0
votes

You will need to return only the columns for ValueMember & DisplayMember

var qry = (from u in dc.Suppliers
            select new { a.SupplierID, a.CompanyName}).ToList();
            comboBox2.ValueMember = "SupplierID";
            comboBox2.DisplayMember = "CompanyName";
            comboBox2.DataSource = qry;
0
votes

It is necessary to initialize the combobox properties before changing its ValueMember, like this:

        **comboBox2.DataSource = null;**
        if (ComboBox1.Text == "Customers")
        {
            var qry = (from u in dc.Customers
                       select new { u.CustomerID, u.CompanyName }).ToList();
            comboBox2.ValueMember = "CustomerID";
            comboBox2.DisplayMember = "CompanyName";
            comboBox2.DataSource = qry;
        }
        if (ComboBox1.Text == "Suppliers")
        {
            var qry = (from u in dc.Suppliers
                       select new { u.SupplierID, u.CompanyName }).ToList();
            comboBox2.ValueMember = "SupplierID";
            comboBox2.DisplayMember = "CompanyName";
            comboBox2.DataSource = qry;
        }