Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Avoiding Whitespace Clicking in CheckedListBox

0.00/5 (No votes)
3 Sep 2013 1  
Prevent a checkedListBox from toggling check state when clicking whitespace

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) //checks the item being checked before it does
{
    //if the click isn't on an item (and on the white space)
    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).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here