简体   繁体   English

从另一个静态类更改文本字段的文本

[英]change text of textfield from another static class

Here is my code. 这是我的代码。

Main class 主班

namespace winapp
{
public partial class Main_Form : Form
{

    //Here is textfield1

    public Main_Form()
    {
       InitializeComponent();
    }
 }

the other class 另一类

namespace winapp
{
public partial class second: Form
{
   static Main_Form main_form = new Main_Form();
   string sss = "12345";

    public second()
    {
        InitializeComponent();
    }

    private void but_Click(object sender, EventArgs e)
    {
       //I want to change the text from here
        main_form.textbox1.text = this.sss;
    }    

Like above, I want to change the text of a textField in the main class with second class. 像上面一样,我想用第二类在主类中更改textField的文本。
But my the text of textfiled does not change. 但是我的textfiled的文本没有改变。

Regurd if anyone can help me. 如果有人可以帮助我,我感到很遗憾。

The issue is that you're creating a brand new Main_Form . 问题是您要创建一个全新的Main_Form Instead you can pass your instance of Main_Form to second : 相反,您可以将Main_Form的实例Main_Formsecond

public partial class Second : Form
{
    private readonly Main_Form _mainForm;

    public Second(Main_Form mainForm) {
        _mainForm = mainForm;
    }
}

I would then create a property on MainForm to access the textbox: 然后,我将在MainForm上创建一个属性以访问文本框:

public ... Main_Form : Form
{
    public string MyText {
        get { return textbox1.Text; }
        set { textbox1.Text = value; }
    }
}

I'm not sure where you create your second form but it would now look like this as long as you're creating it in Main_Form : 我不确定您在哪里创建second窗体,但是现在只要在Main_Form创建它,它就会看起来像这样:

Second secondForm = new Second(this);

And then second can access Main_Form's MyText property which will set the textbox. 然后second可以访问Main_Form's MyText属性,该属性将设置文本框。

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

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