改变文本框从另一个类

改变文本框从另一个类

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

问题描述

我试图改变位于一个文本框的值

I'm trying to change value of a text box located in

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);
}

从另一个类,我叫它像

From another class I'm calling it like

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

我也得到空白输出。我也试过关键字添加静态到回声的方法,但我得到了相同的结果。我搜索了堆栈 溢出,并没有得到任何的解决方案工作。有一件事触发了我,如果我添加 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?

推荐答案

每次说新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);
    }

}

请注意,您访问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);
}

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

08-30 08:09