Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check only one ListViewItem at time

I'm developing a smart device project using the Compact Framework.

I have a ListView with several checkable ListViewItems: 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?

like image 925
Nick Avatar asked Dec 04 '22 13:12

Nick


1 Answers

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.

like image 88
Nyuno Avatar answered Dec 15 '22 04:12

Nyuno