Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does listview fire event indicating that checked item is unchecked after adding

I'm adding items to a listview (c# winforms app) via the following code:

var IT = new ListViewItem(Term);
IT.Checked = true;
MyListView.Items.Add(IT);

However, immediately after adding the item I receive an event which indicates that the item isn't checked (e.Item.Checked is false).

I then receive a subsequent event which indicates that it is checked (e.Item.Checked is true).

Why am I receiving the first event? Is the checked property being set to false for some reason when I add the item to the list? Seems odd given that I'm setting the checked status to true prior to adding it to my event.

Any help greatly appreciated. Thanks in advance.

like image 565
Richard Avatar asked Sep 21 '11 21:09

Richard


1 Answers

It seems as though when each ListViewItem's CheckBox is added to the ListView it is initially set as unchecked which fires the ItemChecked event.

In your case the CheckBox is then set as checked to match IT.Checked = true; which fires the event again.

This seems to be by design and I do not think there is a method of stopping these events from firing upon load.

One work around (albeit a bit of a hack) would be to check the FocusedItem property of the ListView, as this is null until the ListView is loaded and retains a reference to a ListItem there after.

void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    if (listView1.FocusedItem != null)
    {
        //Do something
    }
}

Hope this helps.

like image 100
jdavies Avatar answered Sep 18 '22 11:09

jdavies