Winform中自制下拉搜索多选框时,遇到的绑定的问题?

背景:尝试使用CheckedListBox跟TextBox自制一个下拉搜索多选框。

想法如下:控件初始化时在CheckedListBox中绑定全部数据,然后监听TextBox的TextChange事件,每当内容变化,那么根据TextBox的Text重新绑定CheckedListBox的数据。

问题:当选中某个选项之后,进行搜索,不做任何选中/取消选中操作,然后清空搜索条件,此时CheckedListBox中没有任何项被选中。

测试:

1.CheckedListBox中的数据项为[{name:"李白",id:1},{name:"贺知章",id:2}]

2.选中李白,贺知章。

3.搜索框中输入  李

4.搜索框中删除  李

结果:

CheckedListBox中没有被选中的内容

 

 

代码如下

        public List<int> result = new List<int>();

// 用户控件初始化
private void DropdownSearchCheckBox_Load(object sender, EventArgs e)
        {
            DataTable dt = SqlHelper.ExecuteDataTable("select * from loginuser", CommandType.Text, null);
            checkedListBox1.DataSource = dt;
            checkedListBox1.ValueMember = "UserID";
            checkedListBox1.DisplayMember = "UserName";
        }

// 搜索
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string sql = "select * from loginuser";
            List<int> tempList = new List<int>();
            tempList.AddRange(result);
            if (!string.IsNullOrWhiteSpace(textBox1.Text))
            {
                sql += $" where username like '%{textBox1.Text}%'";
            }
            DataTable dt = SqlHelper.ExecuteDataTable(sql, CommandType.Text, null);
            checkedListBox1.DataSource = dt;
            checkedListBox1.ValueMember = "UserID";
            checkedListBox1.DisplayMember = "UserName";
            //Thread.Sleep(500);

            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                DataRowView drv = checkedListBox1.Items[i] as DataRowView;
                if (tempList.Exists(c => c == Convert.ToInt32(drv.Row.ItemArray[0])))
                {
                    this.checkedListBox1.SetSelected(i, true);
                }
            }
        }

// 记录选中的值
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            string sb = string.Empty;
            CheckedListBox model = sender as CheckedListBox;
            if(!result.Exists(c=>c==Convert.ToInt32(model.SelectedValue)))
            {
                result.Add(Convert.ToInt32(model.SelectedValue));
            }
            else
            {
                result.Remove(Convert.ToInt32(model.SelectedValue));
            }
            textBox2.Text = sb.Trim(',');
            textBox3.Text = string.Join(",", result.ToArray());
        }

 

 

先清空内容,再循环add试试

for (int i = 0; i < dt .Rows.Count; i++)
{            
    this.checkedListBox1.Items.Add(dt.Rows[i][0], false);//设置不选定                            
}

 

通过断点调试,发现重新绑定数据之后。选项会被清空重新绘制,可是我是在更新DataSource之后再重新让选项被选中,似乎并没有发挥作用。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632