Reputation: 29
I want to make a code by selecting a checkbox from the ListView to automatically select all the checkbox from the ListView.
I'm using visual studio 2005 so I don't have ItemChecked form. Thats why I want to make this by using ListView itemcheck event. Here is my code.
private void lvBase_ItemCheck_1(object sender, ItemCheckEventArgs e)
{
if ( ) // If selecting one checkbox from the ListView
{
for (int i = 0; i < lvBase.Items.Count; i++)
{
// Select all checkbox from the ListView
}
}
else // If unselecting one checkbox from the ListView
{
for (int i = 0; i < lvBase.Items.Count; i++)
{
// Unselect all checkbox from the ListView
}
}
}
Can you help me to fill this out? Or if you have any better idea please share :)
Upvotes: 0
Views: 1943
Reputation: 37020
Note: there's most likely a better way to do this, but this is a pattern I used a long time ago and it worked then. :)
In the event you've shown above, it will be called from the listView, and the ItemCheckEventArgs e
will tell you if the box is checked or not. It actually tells you the state of the checkbox before the check. So if checkbox was unchecked and the user just checked it, e.CurrentValue
will be CheckState.Unchecked
.
Now, the problem we may have if we try to update the state of all the checkboxes inside the ItemCheck
event is that we will recursively call the event each time we check a box. One way around this is to track whether or not the user is calling the event (by checking a box) or we're triggering the event by calling item.Checked = true;
.
Something like this may do the trick:
// Set this to true when our code is modifying the checked state of a listbox item
private bool changingCheckboxState = false;
private void lvBase_ItemCheck(object sender, ItemCheckEventArgs e)
{
// If our code triggered this event, just return right away
if (changingCheckboxState) return;
// Set our flag so that calls to this method inside the
// loop below don't trigger more calls to this method
changingCheckboxState = true;
// Set all the checkboxes to match the state of this one
foreach(ListViewItem item in lvBase.Items)
{
item.Checked = e.CurrentValue != CheckState.Checked;
}
// Now that we're done, set our flag to false again
changingCheckboxState = false;
}
Upvotes: 1
Reputation: 5791
Use the ListViewItem.Selected
property:
foreach(ListViewItem item in lv.Items)
item.Selected = true;
foreach(ListViewItem item in lv.Items)
item.Selected = !item.Selected;
Upvotes: 1