求助!!comboBox.ValueMember 出错 无法绑定到新的显示成员 参数名: newDisplayMember
C#写的winform
想让两个comboBox实现联动效果,需要从第一个comboBox中获取value,但是用comboBox.selectedValue获取总为空,后来照着百度搜到的改,结果出现了如标题所述错误:下面贴上代码:
private void test_Load(object sender, EventArgs e)
{
DataTable deptTable = db.GetDepartmentInfo().Tables[0];//GetDepartmentInfo()是我在business层写的一个方法,用来获取表中的所有数据;
int count = deptTable.Rows.Count;
for (int i = 0; i < count; i++)
{
string did =deptTable.Rows[i][0].ToString();
string dname = deptTable.Rows[i][1].ToString();
comboBoxDept.Items.Add(dname);
comboBoxDept.DataSource = comboBoxDept.Items;
comboBoxDept.ValueMember = "did";//此处为出错行,错误信息为无法绑定到新的显示成员,参数名: newDisplayMember;
comboBoxDept.DisplayMember = "dname";
}
}
我都改了一天了,也没改明白!跪求各位老大救救我啊,帮我解答一下~谢谢!T T
------解决方案-------------------- comboBoxDept.Items.Add(dname);
comboBoxDept.DataSource = comboBoxDept.Items;
comboBoxDept.ValueMember = "did"
砸没看明白呢??一边在add item,一边又在datasouce绑定Items
当然最明显的位置是最后一句,既然datasouce是他自己的Items,这个items又那里来的did属性??(items的类型是ObjectCollection,他可没有did属性)
ps:看了又看,你做的事情好像挺多余的
你直接绑定那个datatable就是了
comboBoxDept.DataSource=deptTable;
comboBoxDept.ValueMember = "did";
comboBoxDept.DisplayMember = "dname";
------解决方案--------------------如果除了数据库的数据外你还要加入几个额外的数据,也可以绑定实体类数组:
class MyItem
{
public string did;
public string dname;
}
....
List<MyItem> vtData=new List<MyItem>();
int count = deptTable.Rows.Count;
for (int i = 0; i < count; i++)
{
MyItem rItem=new MyItem();
rItem.did =deptTable.Rows[i][0].ToString();
rItem.dname = deptTable.Rows[i][1].ToString();
vtData.Add(rItem);
}
comboBoxDept.DataSource = vtData;
comboBoxDept.ValueMember = "did";
comboBoxDept.DisplayMember = "dname";
comboBoxDept.DataSource绑定数据应该放在循环之外,
------解决方案--------------------这样就可以了
C# code
private void test_Load(object sender, EventArgs e)
{
DataTable deptTable = db.GetDepartmentInfo().Tables[0];
comboBoxDept.DataSource = deptTable;
comboBoxDept.ValueMember = deptTable.Columns[0].ColumnName;
comboBoxDept.DisplayMember = deptTable.Columns[1].ColumnName;
}