如何从与linq的combobox绑定中获得valuemember?

时间:2013-12-07 07:52:35

标签: c# linq combobox valuemember

如何从linq

的combobox绑定中获取valuemember
 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" }

我想返回Just ID值;

有什么问题?? !!

2 个答案:

答案 0 :(得分:0)

您必须为ValueMember设置ComboBox,否则它将是您所看到的:

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

然后comboBox1.SelectedValue将返回IDProjectName,具体取决于您设置的ValueMember,假设您将其设置为"ID",那么您可以获得SelectedValue喜欢这样:

var id = (int) comboBox1.SelectedValue;

答案 1 :(得分:0)

您所用的代码错误:

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

正确的代码:

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