简体   繁体   中英

How to change the Text of a Button in One form with a Button click of another Form?

I have two forms . In the first form there is a button with the text "Log In". By clicking this button I will open another form where I will be able to log in using username and password. Then there is a button "Proceed", it will verify the username and password and then close the 2nd form. Then it will change the text of the "Log In" Button in the first form to "Welcome, " + username.

Everything works just fine, but I can't change the text of the button in the 1st form. I understand that I need to refresh the Form1 after closing the Form2 . But I was unable to do it.

I would do it this way, I have something on form2 which records the text I entered.

public partial class Form2 : Form {
    public string InputText = ""; //use this to record whatever is inputed in the Form2 by the user
    //somewhere else in the code
    public void foo(){ //this may be closing event or button pressed event
        InputText = textBoxInForm2.Text; //record the input from `form2` textbox
        this.DialogResult = DialogResult.OK; //mark as ok
    }

    //This is exactly the foo above, but just in case you wonder how the event FormClosing look like:
    //Add this event handler on your Form2
    private void Form2_FormClosing(object sender, FormClosingEventArgs e) {
        InputText = textBoxInForm2.Text; //record the input from `form2` textbox
        this.DialogResult = System.Windows.Forms.DialogResult.OK;
    }
}

Then in your form1 , you could open form2 with ShowDialog . Then if the dialog results the way you want, something like this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        Form2 form2 = new Form2(); //this must be declared in form1
        if (form2.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            textBoxInForm1.Text = form2.InputText; //grab the input text
        }
    }
}

Then update the textBoxInForm1 with whatever value from form2

Edit: in the example I gave, the form2 is created in the form1 constrcution. This obviously may not be always true. But the example is shown to emphasize that the form2 must be within form1 domain to access. In this case, being an object declared in its constructor . You can place where your form2 is created as per necessary: as a property of Form1 class, inside one of the Form1 method, etc

There is no need to return in your form1.

You should create another form class and design it as per your requirement. Then activate this form to accomplish your task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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