Get ID of item selected in ComboBox
c#, entity-framework, linq, winforms
Solution
You need to use `SelectedValue` and `int.TryParse` method. Like this:
int id;
bool result = int.TryParse(cbbilar.SelectedValue.ToString(), out id);
Problem
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`?