Search code examples
c#comboboxms-access-2010

How do I select a value from a combo box to display an associated value in c#


I have a combo box within a WinForm using C# that displays a list of customer names from an MS Access Database. I have another textbox where I want to display the customer ID on the selection of the customer name using the combo box? The code I have used to display the list of names in the combo box is as follows;

public void homeFrm_Load(object sender, EventArgs e)
    {
           OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Carmine_Cycle_Couriers_Database.accdb");
        OleDbDataAdapter da = new OleDbDataAdapter("SELECT CustomerID, FirstName from tblCustomer", cn);
        DataSet dt = new DataSet();
        da.Fill(dt, "FirstName");
        cboCustomerSelect.DataSource = dt.Tables["FirstName"];
        cboCustomerSelect.DisplayMember = "FirstName";
        cboCustomerSelect.ValueMember = "CustomerID";
        cboCustomerSelect.Text = "Select Customer";
    }

Solution

  • You can use Value property of cboCustomerSelect to get the CustomerId. You can use combobox selectedindexchanged event and do the following

    yourTextBox.Text = cboCustomerSelect.Value.ToString();