I'm developing a smart device project using the Compact Framework.
I have a ListView
with several checkable ListViewItem
s: the property CheckBoxes
is true. I need to check only one ListViewItem
at time, so I subscribed the ItemCheck
event:
// I need to know the last item checked
private ListViewItem lastItemChecked;
private void listView_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (lastItemChecked != null && lastItemChecked.Checked)
{
/* I need to do the following to prevent infinite recursion:
i.e. subscribe and then unsubscribe the ItemCheck event. */
listView.ItemCheck -= listView_ItemCheck;
lastItemChecked.Checked = false;
listView.ItemCheck += listView_ItemCheck;
}
lastItemChecked = listView.Items[e.Index];
}
Is there a better way to prevent the infinite recursion and thus the Stack Overflow
?
Well, I think what might be better than juggling with the EventHandlers is checking if the lastItemCheck is a current item from the EventArgs. Like this:
// I need to know the last item checked
private ListViewItem lastItemChecked;
private void listView_ItemCheck(object sender, ItemCheckEventArgs e)
{
// if we have the lastItem set as checked, and it is different
// item than the one that fired the event, uncheck it
if (lastItemChecked != null && lastItemChecked.Checked
&& lastItemChecked != listView.Items[e.Index] )
{
// uncheck the last item and store the new one
lastItemChecked.Checked = false;
}
// store current item
lastItemChecked = listView.Items[e.Index];
}
I think that you'll agree, that re-assigning EventHandlers is a bit worse than simply checking the reference of the stored object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With