Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return result between Windows Forms in C#

Tags:

c#

.net

winforms

I have two Windows Forms (MyApp, Generator), and I need to call Generator from MyApp

Form gen = new Generator();
gen.Show();
string result = gen.IDontKnowWhatToDoHere();

My Generator.cs Form has three TextBox and a Button Ok, so when the user type some text in the three TextBoxes an click Ok I want to get the the Text typed in those three TextBoxes.

Do you have any ideas how I can achieve this.

Thanks.

like image 399
Wassim AZIRAR Avatar asked May 13 '11 08:05

Wassim AZIRAR


People also ask

How do I go back to previous form in C#?

Although if you're not doing anything but returning from the form when you click the button, you could just set the DialogResult property on Form2. button1 in the form designer, and you wouldn't need an event handler in Form2 at all.


2 Answers

I generally use this pattern:

TResult result = Generator.AskResult();

class Generator : Form
{
    // set this result appropriately
    private TResult Result { get; set; }
    public static TResult AskResult()
    {
        var form = new Generator();
        form.ShowDialog();
        return form.Result; // or fetch a control's value directly
    }
}

This makes it work in a single statement, similar to a MessageBox, and does not require making any controls public. You can also include any additional data as parameters to the static method and pass them to the form's constructor or set properties appropriately.

Another benefits includes the ability to, if the need arises, reuse instances of the form.

like image 97
R. Martinho Fernandes Avatar answered Nov 15 '22 16:11

R. Martinho Fernandes


class Generator : Form
{
    public string Text1 { get; private set; }

    void ok_Click (object sender, EventArgs)
    {
        this.Text1 = txt1.Text;
        ...
        this.Close();
    }
}

Form gen = new Generator();
gen.ShowDialog();
string text1 = gen.Text1;
...

class TextInfo
{
    public string Text1 { get; set; }
    ...
}

class Generator : Form
{
    public TextInfo Textinfo { get; private set; }

    public Generator(TextInfo info)
    {
        this.TextInfo = info;
    }

    void ok_Click (object sender, EventArgs)
    {
        this.TextInfo.Text1 = txt1.Text;
        ...
        this.Close();
    }
}

TextInfo info = new TextInfo();
Form gen = new Generator(info);
gen.ShowDialog();
string text1 = info.Text1;
like image 29
abatishchev Avatar answered Nov 15 '22 17:11

abatishchev