Reputation: 43
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
Upvotes: 0
Views: 420
Reputation: 190
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;
}
Upvotes: 3
Reputation: 56
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:
Upvotes: 1