Hi,
I populate a combobox from a recordset of names. I need for the NAME to display but the value to be another column called PERNO. I think I'm supposed to use ValueMember.
Here's my code:
ds = new SqlDataAdapter("select distinct name, perno from empmast order by name", con);
ds.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
cbOfficer.Items.Add(dt.Rows[i]["name"]);
}
cbOfficer.DisplayMember = "name";
cbOfficer.ValueMember = "perno";
officer = cbOfficer.ValueMember;
private void btRefresh_Click(object sender, EventArgs e)
{
MessageBox.Show(officer);
}
As you can see, I inserted a MessageBox just to see the value returned. Unfortunately, it is showing the string of "perno" instead of the database value.
I would greatly appreciate your help in showing my mistake. Thank you.
VulpesPosted Jan 27, 2014, 12:02 PM
ds = new SqlDataAdapter("select distinct name, perno from empmast order by name", con);
ds.Fill(dt);
cbOfficer.DataSource = dt; // bind combobox to datatable
cbOfficer.DisplayMember = "name";
cbOfficer.ValueMember = "perno";
cbOfficer.SelectedIndex = 0; // select first item
private void btRefresh_Click(object sender, EventArgs e)
{
MessageBox.Show(cbOfficer.SelectedValue.ToString());
}
VulpesPosted Jan 27, 2014, 5:47 PM
You set the DataSource property to the DataTable or perhaps a DataView and then set the DisplayMember and ValueMember properties to the names of the appropriate columns.
This also works with 'local' arrays or lists of objects.
The only difficulty which can arise in practice is if you want to remove items from or add items to the ComboBox subsequently. You're not allowed to do this directly and so have to make changes to the underlying data source and then rebind.
Kevin FralickPosted Jan 27, 2014, 4:05 PM
VulpesPosted Jan 27, 2014, 3:06 PM
Setting the DataSource property fixed that and then there was the SelectedValue point which Jasminder drew attention to earlier.
Kevin FralickPosted Jan 27, 2014, 1:00 PM
You guys are both right. Thank you very much. I guess I was setting the value correctly, just not displaying it right.
Jasminder SinghPosted Jan 27, 2014, 11:23 AM