Antonino Antonino - 2 days ago 4
C# Question

Updating a WinForm label value from code without buttons

I have a simple question but I could not find a direct answer anywhere

I have a C# program which executes a counter after the user pushes a "start" button. So 1, 2, 3, etc but the increments are performed with casual different time durations, i.e.


1 -> [4 seconds after] 2 -> [7 seconds after] 3 -> etc


and checked in the program every millisecond

I wanted to put an indication on the GUI to let the user know about the number reached

Counter

I was thinking to obtain it using a label for the word "Counter:"

// CounterLabel
//
this.CounterLabel.Anchor = ((System.Windows.Forms.AnchorStyles)
((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.CounterLabel.AutoSize = true;
this.CounterLabel.Location = new System.Drawing.Point(1090, 35);
this.CounterLabel.Name = "CounterLabel";
this.CounterLabel.Size = new System.Drawing.Size(58, 17);
this.CounterLabel.TabIndex = 52;
this.CounterLabel.Text = "Counter:";


but then I have two questions:

1) do I need a read-only text box to host the changing number

//
// CounterValue
//
this.CounterValue.Anchor = ((System.Windows.Forms.AnchorStyles)
((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.CounterValue.BackColor = System.Drawing.SystemColors.Control;
this.CounterValue.Location = new System.Drawing.Point(1149, 32);
this.CounterValue.Name = "CounterValue";
this.CounterValue.Size = new System.Drawing.Size(84, 22);
this.CounterValue.TabIndex = 53;
this.CounterValue.ReadOnly = true;
//this.CounterValue.Text += this.GetCounterValue();


or there is a way to have it using only the label?

2) how to perform the control to see if we have to update the UI? I mean, the value to display is checked every msec and I want the interface to be updated every msec as well [without using an "update" button to ask to show the value reached]

Thanks in advance to those who will try to help

Answer

1) Yes, you would need read-only text box next to the label.

2) add a method to the form as follows:

void UpdateCounter()
{
    if (InvokeRequired)
    {
        BeginInvoke(new MethodInvoker(UpdateCounter));
        return;
    }
    CounterValue.Text = Counter.ToString();
}

3) call this method everytime the counter is changed.

Or you could use a timer to call the UpdateCounter function.

Comments