Introduction
This piece of code is intended to prevent an issue of having a checkedListBox
with whitespace in it, and when you click the whitespace, it will toggle the state of a selected item (if one is selected).
Background
I came up with this code after I had an issue with a program of mine where a checkedListBox
could have whitespace in it. I had the settings for the item set for checkOnClick
, so when the user would click in the whitespace of the checkedListBox
and had an item selected, it would change the checked state of the item selected.
Using the Code
This piece of code is pretty simple, actually simpler than the one I originally had. Recently, I found myself using this code again, but after reading a comment from Alan N, I found myself looking for a better way to do it.
The original code involved using a MouseUp
event, however now it uses the ItemCheck
event. The ItemCheck
event is called before the actual item's check state changes. The following event looks like the following:
private void checkedListBox1_ItemCheck
(object sender, ItemCheckEventArgs e) {
if (checkedListBox1.IndexFromPoint(checkedListBox1.PointToClient(Cursor.Position).X,
checkedListBox1.PointToClient(Cursor.Position).Y) <= -1)
{
e.NewValue = e.CurrentValue;
}
}
Now the thing is however, the ItemCheck
event does not offer a parameter for getting the cursors location with relation to the checkedListBox
like you might in the MouseUp
event. So to get around this issue, PointToClient
is used. PointToClinet
from how I understand it will give the cursors location in relation to the item it's linked to, which in this case is checkedListBox1
, and not in relation to the cursor's position on the whole screen.
This simple little code works great for the problem listed above, and unlike before where it would actually change the toggle state then revert it back if invalid, this prevents the check all together if it's invalid.
Points of Interest
I spent a while looking for some code to do something like this, but wasn't having a lot of luck. Then I decided to look into it and write something of my own.
History
The code to do this was updated. The newest version is smaller, and more effective. Special thanks to Alan N, whose comment helped me find a better way (the IndexFromPoint
especially).