如何使用linq从组合框绑定中获取valuemember



如何使用linq 从组合框绑定中获取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="项目名称";cmb_projectName.ValueMember="ID";


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

我想返回Just ID值;

怎么了??!!

您的案例中的错误代码:

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

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

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

然后comboBox1.SelectedValue将返回IDProjectName,这取决于您设置的ValueMember,假设您将其设置为"ID",那么您可以得到如下的SelectedValue

var id = (int) comboBox1.SelectedValue;

相关内容

  • 没有找到相关文章

最新更新