Search code examples
c#winformstextboxmdiparentwinapp

C# MdiParent Can't Show Text on Textbox when send value between 2 form


I use this code in my child form

MainMenu f = new MainMenu();
f.tbUserName.Text = "MY TEXT";

so I want to display text in tbUserName but it doesn't show me.

** I don't want to open new window with this code

MainMenu f = new MainMenu();
f.Show();

Solution

  • That code won't work because you're creating a new instance of the object therefore only the new instance will be affected. If you want to affect an open window, make the Label static in the form.designer.cs file, like so:

    private TextBox tbUserName;
    

    becomes

    public static TextBox tbUserName;
    

    Then you remove remove "this." in front of any mention of "tbUserName".

    this.tbUserName.Size = new Size();
    

    becomes

    tbUserName.Size = new Size();
    

    And then in order to change the Label's text value, use the below statement.

    MainMenu.tbUserName.Text = "MY TEXT";