首页 > 解决方案 > 如何在 C# 中动态添加检查 _list_box 中通过复选框选择和取消选择所有项目?

问题描述

我想用一个复选框进行选择/取消选择。我试图获取所选项目的索引。我没能得到这个,所以我试图改变盒子的名字。仍然没有成功。

foreach (var item in DATAsetname_INIlist)
{
    checkedListBox2.Items.Add(item);
}
if (checkedListBox2.Items.Count != 0)
{
    checkedListBox2.Items.Add("Select all");
}

private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    if (checkedListBox2.Items.Count != 0)
    {

          if (checkedListBox2.SelectedItem.ToString() == "Select all")
          {
                 for (int i = 0; i < checkedListBox2.Items.Count; i++)
                 {
                    checkedListBox2.SetItemChecked(i, true);
                 }
                 string changed = "Deselect all";
                 checkedListBox2.SelectedItem =changed;
          }
          if (checkedListBox2.SelectedItem.ToString() == "Deselect all")
          {
            for (int i = 0; i < checkedListBox2.Items.Count; i++)
            {
                checkedListBox2.SetItemChecked(i, false);
            }
            string changed = "Select all";
            checkedListBox2.SelectedItem = changed;
          }
    }
}

你能帮忙吗?谢谢你

标签: c#winforms

解决方案


做过快速运动。请相应地修改您的代码。

/// <summary>
/// Check all check boxes and vice versa
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ChkSelectAll_CheckedChanged(object sender, EventArgs e)
{
    //Declare your checkedListBox2 count
    iCount = checkedListBox2.Items.Count;
    if (sender != null)
    {
        for (int i = 1; i <= iCount; i++)
        {
            CheckBox ck = null;
            Control[] chkTest = this.Controls.Find("chkDrive" + i, true);

            if (chkTest.Length > 0)
            {
                if (chkSelectAll.Checked)
                {
                    for (int j = 0; j < chkTest.Length; j++)
                    {
                        ck = (CheckBox)chkTest[j];
                        ck.Checked = true;
                    }
                }
                else
                {
                    for (int j = 0; j < chkTest.Length; j++)
                    {
                        ck = (CheckBox)chkTest[j];
                        ck.Checked = false;
                    }
                }
            }
        }
    }            
}

推荐阅读