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);
}
这篇关于从另一个类更改文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从另一个类更改文本框
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
