C# Windows Forms: Retrieve value from ComboBox ValueMember populated with entity framework

396 Views Asked by At

I have a ComboBox and I populate it from entity framework model.

ComboBox.DataSource = (from x in _context.myTable
                                         where x.isActive == true
                                         select new {
                                                        x.Name,
                                                        x.ID
                                                    }
                                         ).Distinct().ToList();

ComboBox.DisplayMember = "Name";
ComboBox.ValueMember = "ID";
ComboBox.SelectedIndex = -1;
ComboBox.Invalidate();

The problem is that: Each time the Combox selection changes, I want to retrieve the information behind the ID (PK Identity number) column of myTable (SQL Server table), but the ComboBox.SelectedValue returns wrong identity number. Actually, it returns the Index + 1.

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    Console.WriteLine("ComboBox.SelectedValue=" + ComboBox.SelectedValue);        
}

Could you please advise?

1

There are 1 best solutions below

0
Younis On

I also faced same problem and i find out a pretty simple solution. May be there is problem in binding comboBox, if you can try this code for binding comboBox.

using (DatabaseEntities db_entity = new DatabaseEntities())
        {
            comboBox1.DataSource = db_entity.TableName.ToList();
            comboBox1.ValueMember = "ID";
            comboBox1.DisplayMember = "Name";
        }

you can retrieve ValueMember (in your case "ID").

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedIndex > 0)
        {
            int _id = Convert.ToInt32(comboBox1.SelectedValue);
        }
    }