Ruan
Ruan

Reputation: 4283

Change text on a form from within a thread in C#

I'm trying to change the text on my Form1's textbox to "hello there" from within a thread. But when I execute it, I get the error "Object reference not set to an instance of an object." When I check I see that txtboxCheckedFiels has a Null value.

How would I create an Object of that txtbox? (I have multiple threads running of which all should be able to change that text.

Code I've tried:

txtboxCheckedFiles.Invoke(new Action(() =>
                {
                    txtboxCheckedFiles.Text = "Hello there";
                }));

And another way i tried

var t = new Thread(
o => 
{
     txtboxCheckedFiles.BeginInvoke(
         ((Action)(() => txtboxCheckedFiles.Text = "Hello there")));
});

Upvotes: 1

Views: 3135

Answers (2)

P_Rein
P_Rein

Reputation: 510

It might be the same .. but this is what I've always used :

    public void LabelWrite(string value)
    {
        if (InvokeRequired)
            Invoke(new LabelWriteDelegate(LabelWrite), value);
        else
        {
            textBox1.Text = value;
        }
    }
    delegate void LabelWriteDelegate(string value);

works like a charm .. you can basically write whatever you want in the else { } too.

Upvotes: 2

Odys
Odys

Reputation: 9080

First you MUST check if invokation is required, and then you may invoke it. Also, consider checking that there is a handle to the window, which means that windows is up and running (eg. this will fail if you try to load data in the constructor of the form)

if (this.InvokeRequired)
{
    IAsyncResult result = BeginInvoke(new MethodInvoker(delegate()
    {
        // DOSTUFF
    }));

    // wait until invocation is completed
    EndInvoke(result);
}
else if (this.IsHandleCreated)
{
    // DO STUFF
}

Upvotes: 1

Related Questions