How can I access a Button Press from a different Form? C#

98 views Asked by At

So I am creating a Text Editor, and I want to have a popup when the user attempts to close the application asking whether they are sure they want to do this, much like in Windows' Notepad. I am not using MessageBoxes, but instead am using a custom Form. How can I get the info from the Button they press in Form2 and access it in Form1?

Thanks in advance for the responses. If there's any other info I can provide that would be useful, please let me know!

Edit as to what I mean: I have created a form with 3 buttons: Save, Don't Save, and Cancel. I want to get the info as to what they've pressed. Would I simply get the return of the button and go from there?

1

There are 1 answers

0
ManOVision On

You need to have a property to pull the info out of on the secondary form. You'll still want to use ShowDialog() and then you can check the dialog result. This is from memory so the code may not build, but should give you the idea.

On your Form2

public string Text
{
    get { return this.SomeTextBoxOnTheForm.Text; }
    set { this.SomeTextBoxOnTheForm.Text = value; }
}

//called from your "Save" button.
public void Save()
{
    this.DialogResult = DialogResult.Ok;
    this.Close();
}

//called from either your "DontSave" button or your "Cancel" button.
public void Cancel()
{
    this.DialogResult = DialogResult.Cancel;
    this.Close();
}

On your other Form1

public void ShowForm2()
{
    var form = new Form2();

    //you could even set default text here
    form.Text = "Enter a message...";

    var result = form.ShowDialog();
    if( result == DialogResult.Ok )
    {
        var finalText = form.Text;

        //do something with the text
    }
}