Reputation: 35
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";
}
Upvotes: 0
Views: 7329
Reputation: 10026
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";
}
}
Upvotes: 1
Reputation: 6130
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
Upvotes: 0
Reputation: 116438
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";
Upvotes: 1