0

I have two tables in database, Notes and Categories (with Notes having a foreign key to Categories).

I have loaded data from table Notes and in combobox from table category.

Now I need to select the same category(foreign key) as in note in the combobox.

My code is :

DataTable dtCat = qc.getCategory();
cmbCategory.DataSource = dtCat;
cmbCategory.DisplayMember = "categoryName";
cmbCategory.ValueMember = "categoryId";
cmbCategory.SelectedValue = "categoryId";
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
D-D
  • 13
  • 5
  • SelectedValue shouldn't be the column name. Check here for an answer https://stackoverflow.com/questions/2864065/c-sharp-set-combo-item-with-selectedvalue – Andez Jul 13 '18 at 13:59
  • @Andez i tried this , it shows '-1' `MessageBox.Show(cmbCategory.FindStringExact("Bird").ToString());` – D-D Jul 13 '18 at 15:23

1 Answers1

0

Try this:

DataTable dt = new DataTable();
dt.Columns.Add("categoryName");
dt.Columns.Add("categoryId");

dt.Rows.Add(new object[] {"Cat1", "1"});
dt.Rows.Add(new object[] {"Cat2", "2"});
dt.Rows.Add(new object[] {"Cat3", "3"});

this.comboBox1.DisplayMember = "categoryName";
this.comboBox1.ValueMember = "categoryId";

this.comboBox1.DataSource = dt;

this.comboBox1.SelectedValue = dt.Rows[1]["categoryId"]; // select Cat2

So you can specify the selected value by the categoryId column in the Row Values of the DataTable.

Andez
  • 5,588
  • 20
  • 75
  • 116