一、基础设置
单击触发选择效果:需要选择下面这个为True

二、代码实现
1.设置数据源
cs
/// <summary>
/// 为CheckBoxList设置数据源
/// </summary>
/// <param name="checkedListBox1"></param>
/// <param name="data"></param>
private void SetCheckListSource(CheckedListBox checkedListBox1, List<string> data)
{
foreach (var item in data)
{
checkedListBox1.Items.Add(item);
}
}
2.设置全选和取消全选
cs
/// <summary>
/// 全选和取消全选(True=全选)
/// </summary>
private void SetCheckListAllStatus(CheckedListBox checkedListBox1, bool v)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemChecked(i, checkBox1.Checked);
}
}
3.获取选中项目和非选中项目
cs
/// <summary>
/// 获取CheckedListBox数据(True=获取选中的项目,False=获取未选中的项目)
/// </summary>
private List<string> GetCheckedListBoxData(CheckedListBox checkedListBox1, bool isSelect=true)
{
List<string> result = new List<string>();
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
bool isChecked = checkedListBox1.GetItemChecked(i);
// 根据 isSelect 的值来决定是获取选中的项目还是未选中的项目
if (isSelect)
{
if (isChecked)
result.Add(checkedListBox1.Items[i].ToString());
}
else
{
if (!isChecked)
result.Add(checkedListBox1.Items[i].ToString());
}
}
return result;
}