views:

75

answers:

1

I try to add a row to a listView

listView1.Items.AddRange(new ListViewItem[] { item1 });

from a different thread to the one in which it was created and it throws an Exception.

Can anyone help me understand how to do this correctly?

+9  A: 

You can use Control.Invoke() to execute your code back on the UI thread:

listView1.Invoke(
    new MethodInvoker(delegate(){ 
        listView1.Items.AddRange(new ListViewItem[] { item1 };
);
Justin Niessner
it have to work?
rebel_UA
Using the generic type 'System.Action<T>' requires 1 type arguments
rebel_UA
What version of .NET and C# are you using. Also, is that code snippet your actual code...or was that simply an example?
Justin Niessner
@rebel_UA: The non-generic `Action` delegate is only available in framework 3.5 and later. Just declare a parameterless delegate that you can use instead: `public delegate void InvokeAction();`.
Guffa
@Guffa @rebel_UA - Modified my answer a bit to not use the Action delegate.
Justin Niessner
I use VS2010 and .NET Framework 4.0
rebel_UA
Thank, Justin Niessner, now all work.
rebel_UA