Search code examples
c#comboboxvaluemember

Programmatically select an item in combobox by using its ValueMember property


I have a method that gets the ComboBox object and the query to be loaded on its items.

The method also asks for 2 other items:

1.The DB table's column name and sets it into the Combobox's DisplayMember property

2.The id of each record under that DB table column name and sets it into the Combobox's ValueMember property

public void DatabaseColumnRecordsToCombobox(ComboBox cbx, String query, String displayMember, String valueMember)
{
    try
    {
        cmd = new MySqlCommand(query, connection);
        da = new MySqlDataAdapter(cmd);
        tbl = new DataTable();
        da.Fill(tbl);
        cbx.DataSource = tbl;
        cbx.DisplayMember = displayMember;
        cbx.ValueMember = valueMember;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        this.CloseConnection();
    }
}

I use the method by creating a query with 2 columns, the Id and its corresponding Name. And storing it in the ComboBox's DisplayMember and ValueMember:

DatabaseColumnRecordsToCombobox(cmbSupplier, "SELECT Id, Supplier_Name FROM Supplier WHERE Enable_Flag=1 ORDER BY Supplier_Name", "Supplier_Name", "Id");

I apologize for the long introduction, I just want you all to understand how my program works before telling my problem. So the problem is how do I select the default item of DataGridView by using the ComboBox's ValueMember property?

All I know in programatically selecting an item is by using cmbCategory.SelectedItem = "Supplier A" but what I need is to select by using the ValueMember. This way I can set the default item by Id.


Solution

  • Just use SelectedValue instead:

    comboBox1.SelectedValue = "2";
    

    A very simple example just to show what i mean:

            DataTable dt = new DataTable();
            dt.Clear();
            dt.Columns.Add("Id");
            dt.Columns.Add("Supplier_Name");
            DataRow r = dt.NewRow();
            r["Id"] = "1";
            r["Supplier_Name"] = "Supplier A";
            dt.Rows.Add(r);
            r = dt.NewRow();
            r["Id"] = "2";
            r["Supplier_Name"] = "Supplier B";
            dt.Rows.Add(r);
            r = dt.NewRow();
            r["Id"] = "3";
            r["Supplier_Name"] = "Supplier C";
            dt.Rows.Add(r);
    
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "Supplier_Name";
            comboBox1.ValueMember = "Id";
    
            //This will set the ComboBox to "Supplier B"
            comboBox1.SelectedValue = "2";