这是我的代码。我想在用户选中/取消选中CheckedListBox中的项目时更新DataSource。但是当我转储数据源时,没有任何改变。为什么呢?
BindingSource source = new BindingSource();
IList<MyStr> list = new List<MyStr>();
list.Add(new MyStr() { Index = 0, Name = "A", Checked = false });
list.Add(new MyStr() { Index = 1, Name = "B", Checked = false });
list.Add(new MyStr() { Index = 2, Name = "C", Checked = true });
list.Add(new MyStr() { Index = 3, Name = "D", Checked = false });
list.Add(new MyStr() { Index = 4, Name = "E", Checked = false });
source.DataSource = list;
((ListBox)this.cbList).DataSource = source;
((ListBox)this.cbList).DisplayMember = "Name";
((ListBox)this.cbList).ValueMember = "Checked";
public class MyStr
{
public int Index { get; set; }
public String Name { get; set; }
public bool Checked { get; set; }
}
答案 0 :(得分:0)
不幸的是,CheckedListBox不支持该功能,这就是为什么在设计器中隐藏了DataSource属性的原因。
你必须自己做管道工程:
((ListBox)this.cbList).DataSource = source;
((ListBox)this.cbList).DisplayMember = "Name";
((ListBox)this.cbList).ValueMember = "Checked";
for (int i = 0; i < list.Count; ++i) {
cbList.SetItemChecked(i, list[i].Checked);
}
this.cbList.ItemCheck += (sender, e) => {
list[e.Index].Checked = (e.NewValue != CheckState.Unchecked);
};