Possible Duplicate:
Why am I getting this error:“Cross-thread operation not valid: Control lbFolders accessed from a thread other than the thread it was created on.”?
I am new in winforms.In my code I am updating progress bar with for loop and now I need to update a Label in the form the loop count as shown below -
public partial class Form1 : Form { public Form1() { InitializeComponent();
Shown += new EventHandler(Form1_Shown); // To report progress from the background worker we need to set this property backgroundWorker1.WorkerReportsProgress = true; // This event will be raised on the worker thread when the worker starts backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); // This event will be raised when we call ReportProgress backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged); } private void Form1_Load(object sender, EventArgs e) { } void Form1_Shown(object sender, EventArgs e) { // Start the background worker backgroundWorker1.RunWorkerAsync(); } // On worker thread so do our thing! void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Your background task goes here for (int i = 0; i <= 100; i++) { label1.Text = "Trade" + i; // Report progress to 'UI' thread backgroundWorker1.ReportProgress(i); // Simulate long task System.Threading.Thread.Sleep(100); } } // Back on the 'UI' thread so we can update the progress bar void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { // The progress percentage is a property of e progressBar1.Value = e.ProgressPercentage; } }
but while accessing label1,it is throwing error -
Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.
How can I update text of label1
Update your label in your progress handler instead of inside the worker thread.
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar - and our label :)
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Trade{0}",e.ProgressPercentage);
}
You can only access the control from the thread where it was created(that is, the UI thread). In other threads(like your BackgroundWorker), you need to use Control.BeginInvoke.
label1.BeginInvoke(delegate { label1.Text = "Trade" + i; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With