Matt J Matt J - 1 month ago 5
C# Question

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?

Answer

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

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