'Get ID of item selected in ComboBox

I have a ComboBox that gets filled with items from my database. I'm trying to get the ID of the item that is selected in the ComboBox, but nothing I've tried seems to be working.

int id = cbbilar.SelectedIndex + 1;

This is how I have it right now, it's very inefficient and stops working if the first items in the database are removed

var cars = (from z in db.Bilar 
            select new { Value = z.Id, Names = z.Marke.Namn + " "  + z.Namn }).ToList();
cbbilar.DataSource = cars;
cbbilar.DisplayMember = "Names";
cbbilar.ValueMember = "Value";
cbbilar.SelectedIndex = 0;

This is the code for my Combobox. How do I make it fetch the ID of the SelectedItem?



Solution 1:[1]

You need to use SelectedValue and int.TryParse method. Like this:

int id;
bool result = int.TryParse(cbbilar.SelectedValue.ToString(), out id);

Solution 2:[2]

Here is what I got done:

comboBoxPickupLoc.DataSource = pickupLocationRepo.GetPickupLocations();
comboBoxPickupLoc.DisplayMember = "LocationName";
comboBoxPickupLoc.ValueMember = "Id";
comboBoxPickupLoc.SelectedIndex = -1;

and then you can get the Id value as shown below

  object value = comboBoxPickupLoc.SelectedValue;
  MessageBox.Show(value.ToString());

Thanks.

Solution 3:[3]

When ever I am grabbing the SelectedIndex value, I am doing so to place the id into another DataBase for various reasons. I have used the TryParse to do this task but the line below is about as simple as it gets by pulling it as a string rather than parcing to an int.

string id = combobox.SelectedValue.ToString();

Solution 4:[4]

Get ID of item selected in WPF ComboBox

Country & State are your model classes.

code =>

Country country_selected = (Country)DDCountry.SelectedValue;  
State state_selected = (State)DDState.SelectedValue;  
int country_id = country_selected.country_id;
int state_id = state_selected.state_id;      

Solution 5:[5]

I know this is an old question, but here is another way to take information form the db to the comboBox.

   private void userControl_Load(object sender, EventArgs e)
   {
      scon.Open(); //--DB Connection
      string query = "SELECT * FROM AssetTypes"; //Query

      SqlDataReader row;
      SqlCommand scmd = new SqlCommand(query,scon);
      row = scmd.ExecuteReader();

      if (row.HasRows)
      {
         while (row.Read())
         {
            AssetTypeComboBox.Items.Add(row["AssetTypesName"].ToString());
         }
      }
      scon.Close();
   }

to get the ID:

int itemID = AssetTypeComboBox.SelectedIndex + 1; //returns the ID number in the DB. provided the ;list was not sorted.

worked like a charm for me, maybe it can help others in future if they are struggling and do not understand much.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user2662006
Solution 3 Dave Hampel
Solution 4 Suraj Rao
Solution 5