I have a CheckBox that allows me to select or deselect all items in a CheckListBox. What I want is for it to show me the third state when all the elements of the CheckListBox are not selected or deselected.
That is to say that what I find is with these situations:
and what I want is that when all the elements of the CheckListox are not selected or deselected, it is shown like this:
The code that I have tried to do so that these conditions are met is the following:
private void ckbSeleccionarSoftware_CheckStateChanged(object sender, EventArgs e)
{
if (ckbSeleccionarSoftware.CheckState == CheckState.Checked)
{
for (int i = 0; i < clbSoftware.Items.Count; i++)
clbSoftware.SetItemChecked(i, true);
}
else if (ckbSeleccionarSoftware.CheckState == CheckState.Unchecked)
{
for (int i = 0; i < clbSoftware.Items.Count; i++)
clbSoftware.SetItemChecked(i, false);
}
else
{
for (int i = 0; i < clbSoftware.Items.Count; i++)
{
if (clbSoftware.GetItemChecked(i) == true && clbSoftware.GetItemChecked(i+1) == false)
{
ckbSeleccionarSoftware.CheckState = CheckState.Indeterminate;
}
}
}
}
I have used the CheckedStateChange event to show me the different states depending on the CheckListBox.
Given that when the state of an item in the CheckListBox changes, the CheckBox must change and vice versa, we create a variable to know about and not interfere with the change operation, since by modifying the state we are firing state change events.
We create a method for updating the CheckListBox, note that we activate OnUpdating at the beginning to know that we are operating and we deactivate it at the end:
On the other hand, we also create a method for updating the CheckBox :
Well, now we only have to implement the events, in the case of the CheckBox it would be the following:
And for the CheckListBox it would be this one:
Note that we have momentarily disabled/enabled the subscription to the event to be able to assign the new value and ensure in this same method of its state change, without generating additional events.