0

I want to display a progress bar when fetching data to textbox using backgroundWorker. But when debugging, it raised an the following error:

I have read the similar case but It cannot solve my problem.

System.InvalidOperationException: Cross-thread operation not valid with Texbox txtResults.

I am new to C# , please help me! Thanks!

private void btnCheckProcStep_Click(object sender, EventArgs e)
        {
            lblStatus.Text = "";
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
            else
            {
                progressBar1.Visible = true;
                progressBar1.Value = progressBar1.Minimum;

                backgroundWorker1.RunWorkerAsync();
            }
        }
        private void SetText(string text)
        {
            if (this.txtResults.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtResults.Text = text;
            }
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                txtResults.Clear();
                DataTable dtx = new DataTable();
                foreach (DataGridViewRow row in grdMametanCheckList.Rows)
                {
                    var _MAMETAN_NO = row.Cells[0].Value.ToString();
                    dtx = get_Missing_Proc_Inst_Seq(_MAMETAN_NO);

                    foreach (DataRow dr in dtx.Rows)
                    {
                        txtResults.Text += row.Cells[0].Value.ToString() + "," + dr[0].ToString() + Environment.NewLine;
                    }
                }
                for (int i = 0; i <= 100; i++)
                {
                    SetText(i.ToString() + " %");
                    backgroundWorker1.ReportProgress(i);
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }            
        }



private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (!backgroundWorker1.CancellationPending)
        {
            lblStatus.Text = "Processing ... " + e.ProgressPercentage + "%";
            progressBar1.Value = e.ProgressPercentage;
        }
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            lblStatus.Text = e.Error.Message;
        }
        else
        {
            lblStatus.Text = "Done";
            progressBar1.Value = 0;
            progressBar1.Visible = false;
        }
    }

The error occur when backgroundWorker DoWork.

EDITED: added

              foreach (DataRow dr in dtx.Rows)
                    {
                        txtResults.Text += row.Cells[0].Value.ToString() + "," + dr[0].ToString() + Environment.NewLine;
                        SetText(txtResults.Text.ToString());
                    }
Cát Tường Vy
  • 398
  • 6
  • 32
  • Hi and welcome to SO; please ensure you search the web for an answer to your problem before asking here, chances are it’s been seen before. Be sure to use any error message / code you can see as part of your search. If you then need to ask here, please ensure you include what you expected to happen, and what you’ve done to try and fix it yourself (including research!) - this helps us answer quicker, and it helps you avoid getting voted down or flagged. – Clint May 19 '18 at 05:20
  • As has been said, there are plenty of answers to this. Given that your problem also relates to a progress bar you may want to look at part 3 of this [accepted answer](https://stackoverflow.com/questions/48970034/how-to-sync-progress-bar-with-a-function-execution/48978892#48978892), and use the `RunOnUiThread` approach with both of your callback methods. – Richardissimo May 19 '18 at 05:41
  • It is differrent case. It cannot solve my problem. I set: txtResults.Text += row.Cells[0].Value.ToString() + "," + dr[0].ToString() + Environment.NewLine; SetText(txtResults.Text.ToString()); – Cát Tường Vy May 19 '18 at 05:46
  • Could you explain *why* you think it's a different case? You're modifying your UI within `backgroundWorker1_DoWork`, which doesn't run on the UI thread. – Jon Skeet May 19 '18 at 05:47
  • Yes, I added SetText(txtResults.Text.ToString()); after the txtResults.Text += row.Cells[0].Value.ToString() + "," + dr[0].ToString() + Environment.NewLine; It it still raise same error – Cát Tường Vy May 19 '18 at 05:50
  • I don't understand why you think that would help. You're still accessing `txtResults.Text` in a non-UI thread - that's just not going to work. – Jon Skeet May 19 '18 at 07:43

0 Answers0