我在用户控件中有一个选中列表框。搜索项目时,复选框会被取消选中。我尝试了很多次来解决它,但抛出异常。
最初搜索工作正常。问题出在检查状态。
private DataTable GetDataTable()
{
var dt = new DataTable();
using (var CON = new SqlConnection("Connectionstring"))
using (var cmd = new SqlCommand("Select Property_Name, Property_Id from property", CON))
using (var da = new SqlDataAdapter(cmd))
{
CON.Open();
da.Fill(dt);
}
return dt;
}
private void Searchtext_TextChanged(object sender, EventArgs e)
{
if (checkedListBox1.DataSource is DataTable dt)
{
var str = Searchtext.Text.Trim();
dt.DefaultView.RowFilter = string.IsNullOrEmpty(str)
? null
: $"Property_Name LIKE '%{str}%'";
}
}
private void LoadProperty()
{
checkedListBox1.DisplayMember = "Property_Name";
checkedListBox1.ValueMember = "Property_Id";
checkedListBox1.DataSource = GetDataTable();
}
我已经输入了搜索代码。
该问题很可能发生,因为每次您过滤 CheckedListBox 中的数据时,它都会重新加载数据源,这会导致检查状态重置。
我认为您可以通过在应用过滤器之前保存项目的检查状态并在之后恢复它们来解决此问题,如下所示: `
// store states before you filter
private Dictionary<int, bool> GetCheckedStates()
{
var checkedStates = new Dictionary<int, bool>();
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
var row = (DataRowView)checkedListBox1.Items[i];
int propertyId = (int)row["Property_Id"];
checkedStates[propertyId] = checkedListBox1.GetItemChecked(i);
}
return checkedStates;
}
// then restore check states
private void RestoreCheckedStates(Dictionary<int, bool> checkedStates)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
var row = (DataRowView)checkedListBox1.Items[i];
int propertyId = (int)row["Property_Id"];
if (checkedStates.ContainsKey(propertyId))
{
checkedListBox1.SetItemChecked(i, checkedStates[propertyId]);
}
}
}
private void Searchtext_TextChanged(object sender, EventArgs e)
{
if (checkedListBox1.DataSource is DataTable dt)
{
// Save current checked states
var checkedStates = GetCheckedStates();
var str = Searchtext.Text.Trim();
dt.DefaultView.RowFilter = string.IsNullOrEmpty(str)
? null
: $"Property_Name LIKE '%{str}%'";
RestoreCheckedStates(checkedStates);
}
}
private void LoadProperty()
{
checkedListBox1.DisplayMember = "Property_Name";
checkedListBox1.ValueMember = "Property_Id";
checkedListBox1.DataSource = GetDataTable();
}
` 问题是在应用过滤器之前,您将项目的选中状态保存在字典中。由于字典的作用,过滤数据后检查的状态得以恢复。 现在,即使应用过滤器,CheckedListBox 也会保留选中的项目