简体   繁体   中英

How to display two different columns in one combobox

I want to display the two different columns in one particular combobox. When I run it the Customer ID will display. Here is my code.

void GetRecords2()
{


    SqlCommand cmd = new SqlCommand();
    cmd.Connection = cn;
    cmd.CommandText = "SELECT CustomerID, firstname 
            + ',' + lastname FROM Customer";

    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "Customer");

    cboName.DataSource = ds;
    cboName.DisplayMember = "Customer.firstname, Customer.lastname";


    cboName.ValueMember = "Customer.CustomerID";


}

I see you already are creating a single result column containing the "combined" value. That's have the battle.

But, you need to give your column a name (notice the AS FullName alias):

cmd.CommandText = "SELECT CustomerID, firstname + ',' + lastname AS FullName " +
    "FROM Customer";

So you can reference it later by name:

cboName.DisplayMember = "FullName";

This will work. I find that binding a Dictionary to a ComboBox has much more predictable results.

My approach omits the extra SQL syntax, DataSet , and SqlDataAdapter .

Instead I use the SqlDataReader to place the desired information into a Dictionary and then I bind that Dictionary as the DataSource of the Combobox .

void GetRecords2()
{         
    Dictionary <int, string> myDict = new Dictionary<int, string>();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = cn;
    cmd.CommandText = "SELECT CustomerID, firstname, lastname FROM Customer";

    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
       myDict.Add(Convert.ToInt32(reader["CustomerID"]), 
            reader["firstname"].ToString() + " " + reader["lastname"].ToString());
    }

    if (myDict.Count > 0)
    {
       cboName.DataSource = new BindingSource(myDict, null);
       cboName.DisplayMember = "Value";            
       cboName.ValueMember = "Key";  
    }          
}

Check this:

void GetRecords2()
{
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = cn;
    cmd.CommandText = "SELECT CustomerID, firstname 
            + ',' + lastname FullName FROM Customer";

    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds, "Customer");

    cboName.DataSource = ds;
    cboName.DisplayMember = "FullName";


    cboName.ValueMember = "CustomerID";
}

To get selected value :

string customerid = cboName.SelectedValue.toString(); //CustomerID: 1

To get selected item

string fullname = cboName.SelectedItem.Text;  //FullName :  John Hawkins

Best Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM