Get ID of item selected in ComboBox

17,480

Solution 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

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.

Share:
17,480
 Matt J
Author by

Matt J

Updated on June 04, 2022

Comments

  •  Matt J
    Matt J about 2 years

    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?