I have a list view with two groups. I want it so that when I check an item it moves to the second group and when I uncheck it, it moves back to the first.
Here is the code I have tried so far:
private void lstServices_ItemChecked(Object sender, ItemCheckedEventArgs e)
{
foreach (ListViewItem item in lstServices.Items)
{
if (item.Checked)
{
item.Group = lstServices.Groups[1];
}
else
{
item.Group = lstServices.Groups[0];
}
}
}
Firstly I find it buggy. When I tick something it does tend to move to the second group, but when I untick it sometimes it goes back to the first group, sometimes they just wont untick at all and I can't work out why.
Secondly I think this is a messy way to do it, each time something is checked I'm checking the whole list and then moving accordingly. I'm assuming there is a way to address just the item I have just checked but I can't work out how!
To get rid of the loop, you must do something like this:
private void lstServices_ItemChecked(Object sender, ItemCheckedEventArgs e)
{
ListViewItem item=e.Item;
if (item.Checked)
{
item.Group = lstServices.Groups[1];
}
else
{
item.Group = lstServices.Groups[0];
}
}
The ItemCheckedEventArgs variable e
has one property, returning the ListViewItem that fired the event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.