我有一个ComboBox,其DataSource设置为DataTable的一个实例。当行添加到DataTable时,它们显示在ComboBox中而没有其他代码,但是当删除行时,ComboBox保持不变。我的代码的简短摘要:
ComboBox selector = new ComboBox();
DataTable tbl = new DataTable();
PopulateTable()
{
DataRow row1 = tbl.NewRow();
row1["field1"] = 1;
row1["field2"] = "Some Text";
tbl.Rows.Add(row1);
DataRow row2 = tbl.NewRow();
row2["field1"] = 2;
row2["field2"] = "More Text";
tbl.Rows.Add(row2);
}
PopulateSelector()
{
selector.DisplayMember = "field2";
selector.ValueMember = "field1";
selector.DataSource = tbl;
}
RemoveRow()
{
tbl.Rows[0].Delete();
}
此时,ComboBox 显示是正确的,但点击它会将其重置为以前的数据。 DataTable保持正确,删除行导致该实例没有问题,我只是不能使ComboBox反映更改。
答案 0 :(得分:2)
试试这个:
PopulateSelector()
{
selector.DataSource = null;
selector.DisplayMember = "field2";
selector.ValueMember = "field1";
selector.DataSource = tbl;
}
RemoveRow()
{
tbl.Rows[0].Delete();
PopulateSelector()
}
答案 1 :(得分:1)
您可以在数据表和组合框之间使用bindingsource并调用ResetBindings