Changing text box from another class(从另一个类更改文本框)
问题描述
我正在尝试更改位于
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);
}
这篇关于从另一个类更改文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从另一个类更改文本框
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
