private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (checkedListBox1.GetItemChecked(i) == false)
{
...
}
else
{
...
}
}
For some reason when the code above executes, it does the opposite of what I'd like it to do. When an item is checked for the first time it doesn't do anything, however, when it is unchecked it does what's in the else statement (again, opposite of what it's supposed to do). Is there some property that I'm forgetting about here?
You should use e.NewValue
instead of checkedListBox1.GetItemChecked(i)
. The reason being that checkedListBox1.GetItemChecked
is a cached state, because the ItemCheck
event occurs before the internal value is updated.
This'll work as you are expecting:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
...
}
else
{
...
}
}
Secondly, as to why the first time you click the checkbox, it doesn't react: that's because the CheckedListBox
object requires the item to be highlighted before changing the checkbox value through mouse clicks.
In order to achieve a similar effect, set checkedListBox1.CheckOnClick = true
. This will cause the checkbox to become checked whenever clicking on the checkbox or on the list item itself.