How can I get valuemember from combobox binding with linq?

Taher picture Taher · Dec 7, 2013 · Viewed 9.3k times · Source

How can I get valuemember from combobox binding with linq

 cmb_projectName.DataSource = linq1.tbl_Projects.Select(c => new {c.ID,c.ProjectName }).ToList();

int projectID = Convert.ToInt32( cmb_projectName.SelectedValue);

cmb_projectName.DisplayMember = "ProjectName"; cmb_projectName.ValueMember = "ID";


cmb_projectName.SelectedValue ==> return {ID = 1, ProjectName = "projectname1" }

I want to return Just ID value;

What's the problem ??!!

Answer

King King picture King King · Dec 7, 2013

You have to set the ValueMember for your ComboBox, otherwise it will be what you saw:

comboBox1.ValueMember = "ID";
//or
comboBox1.ValueMember = "ProjectName";//It's up to you

Then the comboBox1.SelectedValue will return ID or ProjectName depending on the ValueMember you set, suppose you set it to "ID", so you can get the SelectedValue like this:

var id = (int) comboBox1.SelectedValue;