How can I get valuemember from combobox binding with linq?

9.6k views Asked by At

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 ??!!

2

There are 2 answers

0
Ahmad Hamdy Hamdeen On BEST ANSWER

The wrong code in your case:

cbo.DataSource = StronglyDataTable.OrderBy(x => x.pName)).Select(x => new { x.pID, x.pName });
cbo.DisplayMember = "pName";
cbo.ValueMember = "pID";

The correct code:

cbo.DisplayMember = "pName";
cbo.ValueMember = "pID";
cbo.DataSource = StronglyDataTable.OrderBy(x => x.pName)).Select(x => new { x.pID, x.pName });
0
King King On

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;