We help IT Professionals succeed at work.

How to display the ID value out of a selected item in a Combo box populated by MySQL Data

G F
G F asked
on
Hi,
I'm pulling a list of customers from a MySQL(MariaDB) Database, and putting them into a combo box.  this part works fine.
However I need the associated ID once someone goes through the list and selects from the list.

I'm using c# and Visual Studio 2019.

Here is my method:



private void load_Customer_ComboBox()
        {

            con.Open();
            MySqlCommand sc = new MySqlCommand("SELECT CustomerName from bbb.Customers", con);
            MySqlDataReader reader;

            reader = sc.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("CustomerName", typeof(string));
            dt.Load(reader);
            comboBox1.ValueMember = "Id";
            comboBox1.DisplayMember = "CustomerName";  
           
            comboBox1.DataSource = dt;
           
           
            con.Close();

           

            comboBox1.SelectedIndex = -1;
}

So when someone picks a value from the combo box, I need a way to get the Id that goes along with it.  I've looked on the net and there are many conflicting ways to do it, but not alot of solutions.

I think I have to pull the value out of 'SelectedItemChanged' property of the ComboBox, but not sure how to do it.

Any help would be appreciated.

Thank you!
Comment
Watch Question

Distinguished Expert 2019

Commented:
When this is presented, the user submits a form commonly, the id is what is sent back.
Senior Software Engineer
Top Expert 2009
Commented:
Firstly your query is missing the Id, please replace:
MySqlCommand sc = new MySqlCommand("SELECT CustomerName from bbb.Customers", con);

Open in new window

with:
MySqlCommand sc = new MySqlCommand("SELECT Id, CustomerName from bbb.Customers", con);

Open in new window


and use comboBox1.SelectedValue  to get the the selected Id as shown here.
G FGeneral Manager

Author

Commented:
Thank you Miguel, I should of known that...  :)

G