Jason
Jason

Reputation: 113

Inserting into to listview from another thread

I'm trying to insert an email form another thread to the Form1 listview, but somehow it doesn't work. Here's my code:

    private delegate void InsertIntoListDelegate(string email);
    private void InsertIntoList(string email)
    {
        if (f1.listView1.InvokeRequired)
        {
            f1.listView1.Invoke(new InsertIntoListDelegate(InsertIntoList), email);
        }
        else
        {
            f1.listView1.Items.Add(email);
            f1.listView1.Refresh();
        }
    }

If you can help me then thank you.

Upvotes: 0

Views: 5033

Answers (1)

Phil
Phil

Reputation: 43021

Try this:

    private delegate void InsertIntoListDelegate(string email);
    public void InsertIntoList(string email)
    {
        if(InvokeRequired)
        {
            Invoke(new InsertIntoListDelegate(InsertIntoList), email);
        }
        else
        {
            f1.listView1.Items.Add(email);
            f1.listView1.Refresh();
        }
    }

InsertIntoList is a member of the enclosing control so should be invoked on that control not the list view.

Try this very simple test which works for me:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private delegate void InsertIntoListDelegate(string email);

    public void InsertIntoList(string email)
    {
        if(InvokeRequired)
        {
            Invoke(new InsertIntoListDelegate(InsertIntoList), email);
        }
        else
        {
            listView1.Items.Add(email);
        }
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        Task.Factory.StartNew(() => InsertIntoList("test"));
    }
}

Upvotes: 2

Related Questions