ListViewItem checked status change

All I need to do is enable a few buttons whenever at least one item in my ListView is checked. I tried using ItemCheck event but it seems to execute my code before it actually changes the Checked property of the item I change. That might be just fine if it weren't that if I have a ListView with only one item in, and that item is checked, trying to uncheck it results in enabling of those buttons too, when I really want them to be disabled.

Question is, what event and what kind of code do I need to exploit


Answer this question

ListViewItem checked status change

  • Caga

    That really seems obvious now! Thanks.

  • Junrei

    The ItemCheckEventArgs contains both the old and new check state values.  Use the NewValue property to determine whether the item will be checked or not.  Unfortunately in your case looking at the individual check state of an item is not sufficient because if there are multiple items you only want to change the state if all items have the same state.  Therefore I would recommend that for the event handler you simply check to see if any items are checked via ListView.CheckedItems.Count.  If this is greater than 0 then at least 1 item is checked.  Of course the biggest issue is, as you mentioned, the item hasn't changed state yet.  In this case you'd have to special case if the count is 1 then the item be checked or unchecked may change the final value so you'd have to either add or subtract 1 like so.

    private void OnItemCheck ( object sender, ItemCheckEventArgs e )
            {
                int nCt = listView1.CheckedItems.Count;
                if (e.NewValue == CheckState.Checked)
                    ++nCt;
                else
                    --nCt;

                button1.Enabled = (nCt > 0);               
            }

    In .NET 2.0 you can handle the ItemChecked event instead.  This is raised after the item is checked/unchecked and is better suited for post-change events like enabling or disabling items.

    private void OnItemChecked ( object sender, ItemCheckedEventArgs e )
            {
                button1.Enabled = (listView1.CheckedItems.Count > 0);
            }

    Michael Taylor - 12/10/05

  • ListViewItem checked status change