简体   繁体   English

在C#中的线程内更改表单上的文本

[英]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. 我正在尝试将我的Form1文本框中的文本从一个线程中更改为“hello there”。 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. 当我检查时,我看到txtboxCheckedFiels有一个Null值。

How would I create an Object of that txtbox? 我如何创建该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")));
});

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. 就像一个魅力......你基本上可以在else {}中写下你想要的任何东西。

First you MUST check if invokation is required, and then you may invoke it. 首先,你必须检查是否需要invokation,然后你可以调用它。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM