ArgumentOutOfRangeException When I Remove ListView items

D

dvestal

I have a ListView with checkboxes. I want to remove items when the
checkboxes are unchecked, but to do so yields an
ArgumentOutOfRangeException. Is there an easy way to get around this?

A simple program that illustrates the exception is below:

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

Form frm = new Form();
frm.Load += new EventHandler(frm_Load);
Application.Run(frm);

}

static void frm_Load(object sender, EventArgs e)
{
ListView list = new ListView();
list.CheckBoxes = true;
list.ItemCheck += new ItemCheckEventHandler(list_ItemCheck);

((Form) sender).Controls.Add(list);

ListViewItem item = new ListViewItem("An Item");

list.Items.Add(item);
item.Checked = true;
}

static void list_ItemCheck(object sender, ItemCheckEventArgs e)
{
((ListView) sender).Items.RemoveAt(e.Index);
// Exception is thrown after leaving this handler.
// How can I safely remove this ListView item?
}
}
}
 
A

Ashot Geodakov

You need to handle not the ItemCheck event but ItemChecked:

private void list_ItemChecked( object sender, ItemCheckedEventArgs e )

{

if( !e.Item.Checked )

list.Items.Remove( e.Item );

}



The reason for this exception is that ItemCheck event is the first one in
the event queue that the form must process. For instance, the list view must
re-draw the item with its new (un)checked state. You remove the item from
the list, but the form still tries to access that item in the collection,
and it's gone. Hence, the exception.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top