Question

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

Was it helpful?

Solution

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 });

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top