简体   繁体   中英

Pass data from form2 method to form1 textbox

I have form1 with checkboxes and textbox. When i click on one checkbox, form2 is opened. There is button on form2 which has some funcionality. The last step on this button should be pass text to form1 textbox. How to pass text from form2 method to form1 textbox? Note that i dont want to hide or close form1, or create new instance of form1. How can i achieve this? i checked this, but without success: Send values from one form to another form

U can simply ref Form1 in the Constructor in Form2

public Form2(Form1 frmMain){
    InitializeComponents();
    _FrmMain = frmMain;
}

simply when initializing Form2:

Form2 frm2 = new Form2(this);
frm2.Show();

and now in Form2 you should be able to just change everything by properties:

private void BtnSend_Clicked(object sender, EventArgs e)
{
    _FrmMain.Foo = Bar;
}

An alternative is to use Application.OpenForms witch is a FormCollection containing all open forms owned by the current application. The main one will be Application.OpenForms[0], but this collection will be of Form type, so you need to cast it:

private void BtnSend_Clicked(object sender, EventArgs e)
    {
        ((Form1)Application.OpenForms[0]).Data = "..."; //Data is a property on Form1
    }

You can also do something like this:

private void BtnSend_Clicked(object sender, EventArgs e)
    {
        var myMainForm = Application.OpenForms[0] as Form1;
        if (myMainForm != null)
        {
            myMainForm.Data = "...";
        }
    }

This may not be the best form to solve your problem, but it allows you to do other things like:

  • Search for a specific opened form;
  • Send a signal to all (or part) of opened forms;
  • etc.

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