Search code examples
c#formscheckedlistbox

How to programmatically uncheck a checkbox in a checkedListBoxin a c# form?


I want to write a method that, based on a condition, unchecks only a certain checkbox in a list of checkboxes in c#. I've already assigned the variable "money" a value, determined the index of the checkbox in the list, and assigned a global variable called "index" to its value. Additionally, the string entered for checkedList Name is the same as the name of the checkedListBox.

Here's my code:

public void updateResources(String checkedListName, int cost)
        {
            if (money < cost)
            {
                if (checkedListName == "checkedListBoxBasics")
                {
                    //uncheck box at index
                }
                else if (checkedListName == "checkedListBoxConstruction")
                {
                    //uncheck box at index
                }

                //... more else if statements
            }
            else
            {
                //implement input variables with other external variables
            }
        }

Solution

  • If you already know the index of Checkbox that needs to change the state, you could use CheckListBox.SetItemCheckState method. For example,

     checkedListBoxBasics.SetItemCheckState(index, CheckState.Checked);
    

    or for unchecking

    checkedListBoxBasics.SetItemCheckState(index, CheckState.Unchecked);