Search code examples
c#textboxprogress-bar

Display Progress bar when writing data into textbox in C#


I have to write a long text to a textbox, the screen freezing a long time. So I want to display progress bar when writing text to textbox. Any suggestion with my code? Thank you!

private void btnCheckProcStep_Click(object sender, EventArgs 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;
                    }                   
                }   
            }
            catch (Exception ex)
            {

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

Solution

  • You should use BackgroundWorker to aysnc process

    delegate void SetTextCallback(string text);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        }
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Your background task goes here
            for (int i = 0; i <= 100; i++)
            {
                SetText(i.ToString()+" %");
                backgroundWorker1.ReportProgress(i);
                System.Threading.Thread.Sleep(100);
            }
        }
        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("MEssagebox");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }
    
        private void SetText(string text)
        {
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.Text = text;
            }
        }
    }
    

    Note : Need to run progress bar continue when data is retrieving from database and writing to textbox.