Richard
Richard

Reputation: 101

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.

Upvotes: 10

Views: 6635

Answers (2)

tomascz
tomascz

Reputation: 245

I was experiencing the same dilema and solved it a bit more locally than in jdavies's answer, by simply filtering out the initial "non-checked state not caused by the user" as follows

void listView_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    if (!e.item.Checked && !e.item.Focused)
        return; // ignore this event
    //
    // do something
}

Upvotes: 2

jdavies
jdavies

Reputation: 12894

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.

Upvotes: 19

Related Questions