Key in C# combobox but show different value

I want to do a query on a database that will bring up a customerID (identity) and first and last name.

In the combobox I want to show first and last name but when selected - the value is the customerID. The customerID would run be the subject of another query to auto-populate a windows form.

This is what I have so far - I know the combobox.Items.Add part is wrong - that's where I'm having my issue.

conn = new SqlConnection();
conn.ConnectionString = "my connection string";

SqlDataAdapter da = new SqlDataAdapter("Select * from Customer", conn);
DataTable dt = new DataTable();

da.Fill(dt);

for (int i = 0; i < dt.Rows.Count; i++) 
{
    comboSelectCust.Items.Add(dt.Rows[i]["FName" + "Surname"]);
}

Answers


Since you use a DataTable for this, why not just bind it with a DisplayMember and ValueMember?


You can use the Tag property of ComboBoxItem to set the value (Content is the property that sets the display text):

comboSelectCust.Items.Add(new ComboBoxItem() { 
    Content = dt.Rows[i]["FName"] + dt.Rows[i]["Surname"], 
    Tag = dt.Rows[i]["customerId"]
});

for (int i = 0; i < dt.Rows.Count; i++) 
{
   comboSelectCust.Items.Add(new KeyValuePair<string, int>(dt.Rows[i]["FName"].ToString() +  dt.Rows[i]["Surname"].ToString(), Convert.ToInt32(dt.Rows[i]["customerId"].ToString()));
}

Here is pseudo code how to use DataSource, DisplayMember and ValueMember:

SqlDataAdapter da = new SqlDataAdapter("Select FName || Surename as FullName, customerID from Customer", conn);
DataTable dt = new DataTable();

da.Fill(dt);

comboSelectCust.DataSource = dt;
comboSelectCust.DisplayMember = "FullName";
comboSelectCust.ValueMember = "customerID";

Try this an see

conn = new SqlConnection();
conn.ConnectionString = "my connection string";

SqlDataAdapter da = new SqlDataAdapter("Select (FName+' '+Surname) As Name,customerID from Customer", conn);
DataTable dt = new DataTable();

da.Fill(dt);

comboSelectCust.DisplayMember = "Name";
comboSelectCust.ValueMember = "customerID";
comboSelectCust.DataSource = dt;

I changed the query and add display member and valuemeber properies and assign the data table as the data source


Need Your Help

Python multiprocessing: Event.wait() blocking other processes

python synchronization multiprocessing

I'm working with a toy multiprocessing problem, and event signalling is not working as expected. The multiprocessing documentation refers detail description of Event() to the multithreading

How to set EditText's height to maximum minus other buttons' and EditText's heights?

android android-layout height

I would like to fill the screen with my EditText View which would have all the screen height minus the height of buttons and EditTexts in this Activity