Search code examples
c#winformscheckedlistbox

Determining (de)selected checkbox in a checkedListBox as they are selected


I'm looking to setup a checkedListBox in C#. There will be roughly 50 names displayed in this checkedListBox. I'd like it so that when a name is either selected or deselected, then the program will be able to store it in a variable.

I already have the code so that when a button is pressed, it searches through all off the names in the checkedListBox and returns all those with the selected state:

for (int i = 0; i < nameBox.CheckedItems.Count; i++)
{
          ArrayList.Add(nameBox.CheckedItems[i]);
}

I know that in Java I can use the e.getStateChange() to determine which item has either been selected or deselected:

public void itemStateChanged(ItemEvent e) 
{
        if(e.getStateChange() == ItemEvent.SELECTED)
    {
              ArrayList = checkbox.getText();
        }    
}

Is there anything similar to this Java code that I can use in C# for the checkedListBox?

Any help/advice will be greatly appreciated!


Solution

  • Building on the comment and the link, which has all you need in the example:

    In your form add the private variable, such as a List:

     public class Form1 : System.Windows.Forms.Form
       {
          private System.Windows.Forms.CheckedListBox checkedListBox1;
          private List<string> extraVariable;
    

    then in your constructor or wherever you initialize the checkList, also initialize your extra variable:

          public Form1()
          {
             InitializeComponent();
    
             extraVariable = new List<string>();
    

    Then add your ItemChecked event, where you Add or Remove from your extra variable:

          private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
          {
             if(e.NewValue==CheckState.Unchecked)
             {
                extraVariable.Remove(e.NewValue);
             }
             else
             {
                extraVariable.Add(e.NewValue);
             }
          }