Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
plz help me in this message
Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on.
this my code
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;



namespace Thread
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
               
        
        }
        public void FillLIstBox()
        {
            

            for (int i = 0; ; i++)
            {
                listBox1.Items.Add(i);
            }
        }
        private void BtFill_Click(object sender, EventArgs e)
        {
            System.Threading.Thread thr = new System.Threading.Thread(new System.Threading.ThreadStart(FillLIstBox));
            thr.Start();      
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
    }
Posted

1 solution

You must interact with a control on the UI thread.
You can use Control.InvokeRequired[^] to determine if you're on the UI tread or not. If you're not on the UI thread you have to use Control.Invoke[^] or Control.BeginInvoke[^]

In the case you posted using Invoke wouldn't make sense, but I guess this is not your real case, so you'll want to do something like the following
C#
int j = i;
listBox1.Invoke(() => listBox1.Items.Add(j));
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 25-Sep-11 0:09am    
Correct, a 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900