从另一个类更改文本框 [英] Changing text box from another class

查看:19
本文介绍了从另一个类更改文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改位于

public partial class Form1 : Form

来自另一个班级.我已经尝试过这样的事情

from another class. I've tried something like this

public void echo(string text)
{
    this.textBox1.AppendText(text + Environment.NewLine);
}

我把它叫做另一个类

Form1 cout = new Form1();
cout.echo("Does this work?");

我得到空白输出.我还尝试将 static 关键字添加到 echo 方法,但得到了相同的结果.我搜索了 Stack Overflow 并没有得到任何解决方案.触发我的一件事是,如果我添加 cout.Show() 相同的表单会弹出有效的 textBox1 内容.这是为什么呢?

And I get blank output. I also tried to add the static keyword to the echo method, but I got the same result. I searched over Stack Overflow and didn't get any solution to work. And one thing that triggers me, if I add cout.Show() the same form pop out with valid textBox1 content. Why is that?

为什么它没有立即显示内容?我该如何解决这个问题?

Why it is not showing content right away? And how do I fix this?

推荐答案

每次您说 new Form1() 时,您都在创建该表单的一个独特且单独的实例.相反,您需要在尝试访问表单的类中创建一个变量.例如,让我们在构造函数中传递它:

Each time you say new Form1(), you are creating a distinct and separate instance of that form. Instead, you need to create a variable in the class that you are trying to access your form. For example, let's pass it in the constructor:

public class MyClass {
    public Form1 MyForm;

    public MyClass(Form1 form){
        this.MyForm = form;
    }

    public void echo(string text) {
        this.MyForm.textBox1.AppendText(text + Environment.NewLine);            
    }

}

请注意,您在 echo 方法中访问了 Form1 的特定实例:

Notice that you access the particular instance of Form1 in your echo method:

public void echo(string text) {
     this.MyForm.textBox1.AppendText(text + Environment.NewLine);
}

这篇关于从另一个类更改文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆