简体   繁体   English

将文本写入文本框

[英]writing text into a textbox

I got a form called Form1 and a rich text box called richtextbox1, which is automatically generated, so it's private. 我有一个名为Form1的表单和一个称为richtextbox1的富文本框,它是自动生成的,因此是私有的。

I got another class that connects to a server, I want to output the status of connecting but I can only access the richtextbox1.Text in the Form1 class, I got 2 possible solutions for this, which would be better or is there a better one that I don't know of? 我有另一个连接到服务器的类,我想输出连接状态,但是我只能访问Form1类中的richtextbox1.Text,对此我有2种可能的解决方案,这会更好还是有更好的解决方案我不知道的?

  1. making the textbox public 公开文本框

  2. instead of : 代替 :

     Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); 

creating a form1 object first and using that to store the form that is running: 首先创建一个form1对象,并使用该对象存储正在运行的表单:

//somewhere global
Form1 theform = new Form1();


Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(theform);

Then using the object somewhere in my connection class. 然后在我的连接类中的某处使用该对象。

I'd create a public property in Form1 that you can use. 我将在Form1中创建一个可以使用的公共属性。

Form1.cs

public string TextBoxText
{
    get { return myTextBox.Text; }
    set { myTextBox.Text = value; }
}

You can then set the value from another class. 然后可以从另一个类设置值。

AnotherClass.cs

myForm1.TextBoxText = "Current server status";

How you get access to myForm1 depends on how you're calling the other class. 如何访问myForm1取决于您如何调用另一个类。 For example, you could pass the form into the other class's constructor. 例如,您可以将表单传递给另一个类的构造函数。

private Form1 myForm1 = null;
public AnotherClass(Form1 mainForm)
{
    myForm1 = mainForm;
    myForm1.TextBoxText = "Current server status";
} 

如果要在Form1中创建与服务器通信的类,请向它添加一个事件,并在创建Form1时订阅它。

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

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