none
How to Support Single Click Checkboxs in a ListView in List Mode? RRS feed

  • Question

  • I have a System.Windows.Forms.ListView that is configured in list view and has check boxes enabled.  My user wants to be able to click the text of the entries (Items Collection) and have it check the box.  This is not done by default.  I tried the CheckedListBox first, but that did not meet the need.

    I have added an event handler for selected index changed, but that does not fire when the user clicks on the same element that is already selected (I understand why it does not, and it makes sense). 

    So, I have resorted to using a MouseDown event to determine if an item was selected and to use that as the trigger to change the item's checked state.  This works great except for when the user clicks on the actual check box.  In this case I change it because of the mouse down event and then the control changes it back because the user clicked the check box. 

    I don't know how to figure out of the mouse click was on the check box and not the words of the list view item.  The event ordering of all the clicks and ItemCheck are not done in a manner that lets me stop or prevent the control from performing check box toggle.

    The only thing that has worked is using a custom image list and not using the checkbox.  However, if I can get it working without having to provide my own check box images, that would be preferred.

    So my question is, how can I attain the functionality of checking/unchecking an item in a ListView in List mode when they single click on the label/text of each entry, even if it's currently selected?

    IF MouseDown (or Up or CLick) is the best option, then how do I determine if the checkbox was clicked so that I can skip changing the checked state in my mouse handler?

    Thanks


    Brian R.

    Monday, May 4, 2015 2:47 PM

Answers

  • Consider the MouseClick event and HitTest function, probably in this manner:

    private void listView1_MouseClick( object sender, MouseEventArgs e )

    {

           var where = listView1.HitTest( e.Location );

           if( where.Location == ListViewHitTestLocations.Label )

           {

                  where.Item.Checked = true;

           }

    }

    • Marked as answer by Brian R. _ Monday, May 4, 2015 6:40 PM
    Monday, May 4, 2015 5:36 PM

All replies

  • Consider the MouseClick event and HitTest function, probably in this manner:

    private void listView1_MouseClick( object sender, MouseEventArgs e )

    {

           var where = listView1.HitTest( e.Location );

           if( where.Location == ListViewHitTestLocations.Label )

           {

                  where.Item.Checked = true;

           }

    }

    • Marked as answer by Brian R. _ Monday, May 4, 2015 6:40 PM
    Monday, May 4, 2015 5:36 PM
  • Thank you for that simple and concise response.  That's exactly what I was looking for!

    Brian R.

    Monday, May 4, 2015 6:40 PM