Get ID of item selected in ComboBox

c# entity-framework linq winforms

Question

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?

1
3
10/28/2016 12:17:41 PM

Accepted Answer

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

int id;
bool result = int.TryParse(cbbilar.SelectedValue.ToString(), out id);
2
10/28/2016 11:53:46 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow