Reputation: 5243
I created Listbox with property checkboxes == true
, but the problem that I had was that I was needed to click twice on the line in order to set it checked. I was needed to change it in such a way that I can click on the line just once and the line set as checked. What I did is added mouseClick event:
private void Cbl_folders_MouseDown(object sender, MouseEventArgs e)
{
SelectedListViewItemCollection selectedItemsList = Cbl_folders.SelectedItems;
if(selectedItemsList.Count > Constants.EMPTY_COUNT)
{
selectedItemsList[0].Checked = !selectedItemsList[0].Checked;
}
}
And everything works fine, first, click on the line set the line as checked the second click on the line set the line as unchecked. But then I found out that if you clicked on the line and set this line as checked and then you click on the checkbox on the other line, so your first line that was checked changes the state to unchecked. Why? Because I am tracking mouseDown event and even when I click on the checkbox on the other line mouse down event looks on selected items and the obviously selected item is the first line that was clicked.
I understand that it is possible to add some flags and look where was a click and so on, but it seems overcomplicated, I feel like there is should be a simpler solution.
Upvotes: 0
Views: 591
Reputation: 4660
Handle the MouseDown
event to switch the ListViewItem.Checked property when you click over the label area. To get info about the clicked area, call the ListView.HitTest method which returns a ListViewHitTestInfo object and check the Location property, the property returns one of the ListViewHitTestLocations values.
private void Cbl_folders_MouseDown(object sender, MouseEventArgs e)
{
if (Cbl_folders.CheckBoxes)
{
var ht = Cbl_folders.HitTest(e.Location);
if (ht.Item != null && ht.Location == ListViewHitTestLocations.Label)
ht.Item.Checked = !ht.Item.Checked;
}
}
This way, the items are checked/unchecked by the mouse also when you click outside their check boxes areas (determined by the ListViewHitTestLocations.StateImage
value).
Upvotes: 2