使用linq运行一个项目到sql模型,并将我的组合绑定到bindingsource控件,我有两个组合框,首先显示一个表显示数据库表名(ID,TableName),第二个应该绑定到选定的表中第一个组合,我尝试了这段代码:
private void ComboBox1_TextChanged(object sender, EventArgs e)
{
if (ComboBox1.Text == "Customers")
{
var qry = (from u in dc.Customers
select u).ToList();
comboBox2.ValueMember = "CustomerID";
comboBox2.DisplayMember = "CompanyName";
comboBox2.DataSource = qry;
}
if (ComboBox1.Text == "Suppliers")
{
var qry = (from u in dc.Suppliers
select u).ToList();
comboBox2.ValueMember = "SupplierID";
comboBox2.DisplayMember = "CompanyName";
comboBox2.DataSource = qry;
}
}
使用上面的代码我可以显示第一个组合项目,默认情况下我也可以显示第二个组合项目,但是当我更改第一个组合内容时,我在comboBox2.ValueMember =“SupplierID”中得到错误; :System.ArgumentException未处理 Message =无法链接到新的Value成员。请问如何将combobox2.ValueMember重置为新的字段名称?
答案 0 :(得分:0)
您只需要返回ValueMember&的列。 DisplayMember
var qry = (from u in dc.Suppliers
select new { a.SupplierID, a.CompanyName}).ToList();
comboBox2.ValueMember = "SupplierID";
comboBox2.DisplayMember = "CompanyName";
comboBox2.DataSource = qry;
答案 1 :(得分:0)
必须在更改其ValueMember之前初始化组合框属性,如下所示:
**comboBox2.DataSource = null;**
if (ComboBox1.Text == "Customers")
{
var qry = (from u in dc.Customers
select new { u.CustomerID, u.CompanyName }).ToList();
comboBox2.ValueMember = "CustomerID";
comboBox2.DisplayMember = "CompanyName";
comboBox2.DataSource = qry;
}
if (ComboBox1.Text == "Suppliers")
{
var qry = (from u in dc.Suppliers
select new { u.SupplierID, u.CompanyName }).ToList();
comboBox2.ValueMember = "SupplierID";
comboBox2.DisplayMember = "CompanyName";
comboBox2.DataSource = qry;
}