Home > database >  How to update an Readonly textbox constantly C#
How to update an Readonly textbox constantly C#

Time:10-05

  • I am wondering how to constantly update an readonly textbox.
  • The text box displays a text that always changes.
  • My problem is if I create an loop the application won't start and if I start the loop using a button my application freezes and only it only runs the loop.
  • I also can't use a new thread or the thread that I use to change the variables that are displayed within the text because in this case I just get an error System.InvalidOperationException
  • I was searching for anwser but I couldn't find one.

CodePudding user response:

When using a thread you have to cause your ui update work to run on the UI thread, and that's where you use an "invoke".

There are many ways to achieve your goal, I'll show you two ways you can do it:

  • using a thread (BackgroundWorker is just a fancier way to do that)

  • a Timer (it might be overkill to use a thread just to update a counter if that is what you are intending).

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        bool m_shutdown = false;
        int m_counter = 0;
        Timer m_timer = new Timer();
        BackgroundWorker m_backgroundworker = new BackgroundWorker();
        bool m_usetimerway = false; // change this to true to try the timer way
        Action m_actionupdatecounter;

        public Form1()
        {
            InitializeComponent();

            m_actionupdatecounter = new Action(() =>
            {
                UpdateCounter();
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (m_usetimerway)
            {
                m_timer.Interval = 50;
                m_timer.Tick  = M_timer_Tick;
                m_timer.Enabled = true;
            }
            else
            { 
                m_backgroundworker.DoWork  = M_backgroundworker_DoWork;
                m_backgroundworker.RunWorkerCompleted  = M_backgroundworker_RunWorkerCompleted;
                m_backgroundworker.RunWorkerAsync();
            }
        }
        
        void UpdateCounter()
        { 
            if (this.InvokeRequired)
            {
                // Get it to be run on the UI thread
                this.BeginInvoke( m_actionupdatecounter );
            }
            else
            {
                m_counter  ;
                textBoxCounter.Text = string.Format("{0}", m_counter);
            }
        }

        private void M_timer_Tick(object sender, EventArgs e)
        {
            // This is already on the UI thread because it's a "WinForms" timer

            UpdateCounter();
        }

        private void M_backgroundworker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!m_shutdown)
            { 
                UpdateCounter();

                System.Threading.Thread.Sleep(50);
            }
        }

        private void M_backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            m_shutdown = true;

            // To have a more graceful shutdown, you might want to wait for the
            // background worker to have "completed" before you actually exit
            // your winforms app.
        }
    }
}

enter image description here

  • Related