数据源中的更新重置CheckedListBox复选框 [英] Updates in the DataSource reset CheckedListBox checkboxes

查看:41
本文介绍了数据源中的更新重置CheckedListBox复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CheckedListBox,绑定到BindingList:

I have a CheckedListBox, binded to a BindingList:

private BindingList<string> list = new BindingList<string>();
public MyForm()
{
    InitializeComponent();

    list.Add("A");
    list.Add("B");
    list.Add("C");
    list.Add("D");

    checkedListBox.DataSource = collection;
}

单击某个按钮后,列表将更新:

When a certain button is clicked the list is updated:

private void Button_Click(object sender, EventArgs e)
{
    list.Insert(0, "Hello!");
}

它工作正常,CheckedListBox已更新.但是,当某些项目被选中时,单击按钮不仅会更新列表,还会重置所有未选中的项目.我该如何解决?

And it works fine, the CheckedListBox is updated. However, when some of the items are checked, clicking the button not only updates the list but reset all the items to be unchecked. How can I fix that?

谢谢!

推荐答案

您需要自己跟踪检查状态.

You need to track check-state yourself.

作为一种选择,您可以为包含文本和检查状态的项目创建模型类.然后在 BindingList< T> 刷新项目的检查状态.

As an option, you can create a model class for items containing text and check state. Then in ItemCheck event of the control, set check state value of the item model. Also in ListChenged event of your BindingList<T> refresh check-state of items.

示例

创建 CheckedListBoxItem 类:

public class CheckedListBoxItem
{
    public CheckedListBoxItem(string text)
    {
        Text = text;
    }
    public string Text { get; set; }
    public CheckState CheckState { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

像这样设置 CheckedListBox :

private BindingList<CheckedListBoxItem> list = new BindingList<CheckedListBoxItem>();
private void Form1_Load(object sender, EventArgs e)
{
    list.Add(new CheckedListBoxItem("A"));
    list.Add(new CheckedListBoxItem("B"));
    list.Add(new CheckedListBoxItem("C"));
    list.Add(new CheckedListBoxItem("D"));
    checkedListBox1.DataSource = list;
    checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;
    list.ListChanged += List_ListChanged;
}
private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    ((CheckedListBoxItem)checkedListBox1.Items[e.Index]).CheckState = e.NewValue;
}
private void List_ListChanged(object sender, ListChangedEventArgs e)
{
    for (var i = 0; i < checkedListBox1.Items.Count; i++)
    {
        checkedListBox1.SetItemCheckState(i,
            ((CheckedListBoxItem)checkedListBox1.Items[i]).CheckState);
    }
}

这篇关于数据源中的更新重置CheckedListBox复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆