VS 2022 C# ComboBox operations using WinForms. Adding data from SQL server and later capturing selected value.

Ed Januskis 66 Reputation points
2022-06-03T13:33:41.2+00:00

I am looking the way to allocate data from SQL server table.

  1. get 2 columns (ProductID (int) and ProductName (string) from database table into ComboBox.
  2. show only product name.
  3. Capture selected value in drop down of comboBox. The trick is to get ProductID not ProductName.
  4. This will be used to query product details in different action method.
    NOTE: I can get data into CombBox, but i cannot. capture ProductID. in my code i use “DnameID”

Code:
private void LoadInfo_Load(object sender, EventArgs e)
{
String req = SQL.CmbDrivrList; //getting SQL statment select…form …
try
{
DataSet dsDataFromDB = SQL.GetDataFromDatabase(req); //class getting DB connections and data. No issues here
cmbDriverList.DataSource = dsDataFromDB.Tables[0];
cmbDriverList.SelectedValue = “DnameID”;
cmbDriverList.DisplayMember = “Dname”;
cmbDriverList.DataSource = dsDataFromDB.Tables[0];
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
private void cmbDriverList_SelectedIndexChanged(object sender, EventArgs e)
{
//This is not working i do not know how to assign to txtBox selected Item. This is a test.
tempID.Text = cmbDriverList.SelectedItem.ToString(); //Goal is to capture “DnameID”
}

Developer technologies Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-06-03T14:51:25.357+00:00

    You're close but using the wrong properties. DisplayMember indicates the property on your object to use for the display value. ValueMember indicates the property on your object that holds the actual value. Set that to DnameID and see if your problem goes away.

    cmdbDriverList.DisplayMember = "Dname";
    cmdbDriverList.ValueMember = "DnameID";
    

    Assuming those are names of columns in your table then it should properly bind the data.

    Note also that you have 2 calls to set DataSource. Remove one of them, ideally the first one.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.