Thanh Nguyen
Thanh Nguyen

Reputation: 83

How to update label from another class c#

if i put threadtest() in form1.cs it will work correctly but i want to move to another class it will show error. This is screenshot of error

enter image description here

public partial class Form1 : Form
{
    Thread thread;
    bool loop = true;
    volatile bool _cancelPending = false;
    Stopwatch regularSW = new Stopwatch();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        thread = new Thread(new ThreadStart(() => threadtest()));
        thread.Start();
    }
    public void threadtest()
    {
        while (loop)
        {
            regularSW.Start();
            Thread.Sleep(5000);
            regularSW.Stop();
            label1.Text = "Sleep in: " + regularSW.Elapsed + Environment.NewLine;
        }
    }
}

Upvotes: 0

Views: 1585

Answers (2)

thomas
thomas

Reputation: 1453

The Form1 class is the code-behind class of your windows form. The label named label1 is not defined in Class1.

Can you use events?

Define a different parameter that you can update.

public event Action<string> onStatusChange;
public void threadtest()
{
    var status = "";
    while (loop)
    {
        regularSW.Start();
        Thread.Sleep(5000);
        regularSW.Stop();
        if(null != onStatusChange)
        {
             onStatusChange("Sleep in: " + regularSW.Elapsed + Environment.NewLine);
        }            
    }
}

In Form1 class:

var class1 = new Class1();
class1.onStatusChange += (status) => { label1.Text = status; };
class1.threadtest();      

Upvotes: 2

Dot_NET Pro
Dot_NET Pro

Reputation: 2123

try below code. In your Form1 class button1_Click add the following code:

public partial class Form1 : Form
{
    private void button1_Click(object sender, EventArgs e)
    {
    Class1 class1Object = new Class1();
    thread = new Thread(new ThreadStart(() => class1Object.threadtest(this)));
    thread.Start();
   }
}

Now change your class1 threadtest() function as below:

class Class1
{
     public void threadtest(Form1 form)
     {
    while (loop)
    {
        regularSW.Start();
        Thread.Sleep(5000);
        regularSW.Stop();
        form.label1.Text = "Sleep in: " + regularSW.Elapsed + Environment.NewLine;
    }
}

}

Upvotes: -1

Related Questions