using ComboBox with displaymember and valuemember

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

I have a table in the database that have two kolumns these are
pkid and name.

In the combobox I have set displaymember to name and valuemember to pkid.
This works good. So if a use comboboxName.SelectedValue I get the pkid that
match the displayed name.

To be able to solve a problem I have to get the name that is displayed in
the combobox.
In pseudocode I would like to do this "string selectedName =
comboboxName.DisplayedText;"

As an alternative I can fetch the name from the database because I have the
primary key
but I hope I can get it without using a select query

//Tony
 
Tony Johansson said:
Hello!

I have a table in the database that have two kolumns these are
pkid and name.

In the combobox I have set displaymember to name and valuemember to pkid.
This works good. So if a use comboboxName.SelectedValue I get the pkid
that match the displayed name.

To be able to solve a problem I have to get the name that is displayed in
the combobox.
In pseudocode I would like to do this "string selectedName =
comboboxName.DisplayedText;"

As an alternative I can fetch the name from the database because I have
the primary key
but I hope I can get it without using a select query

ComboBox.Text
 
Another option, and in my opinion a better one, is to retrieve the selected
item and read the properties directly. This way you have access to not only
the displaymember or valuemember but all other properties as well. If you
use a DataTable as the DataSource you will get a DataRowView as SelectedItem.
The DataRowView.Row object is the same as in the DataTable.

protected override void OnLoad(EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("pkid", typeof(int));
dt.Columns.Add("name", typeof(string));

DataRow dr = dt.NewRow();
dr["pkid"] = 1;
dr["name"] = "one";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["pkid"] = 2;
dr["name"] = "two";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["pkid"] = 3;
dr["name"] = "three";
dt.Rows.Add(dr);

ComboBox cb = new ComboBox();
cb.DataSource = dt;
cb.DisplayMember = "name";
cb.ValueMember = "pkid";
Controls.Add(cb);

cb.SelectedValueChanged += new EventHandler(cb_SelectedValueChanged);
}

void cb_SelectedValueChanged(object sender, EventArgs e)
{
DataRowView drv = ((ComboBox)sender).SelectedItem as DataRowView;
int pkid = (int)drv.Row["pkid"];
}
 
Back
Top