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
2 Answers
3
votes
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;
}
1
votes
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.
EventArgs
class that sends back all the values that the subscribers of the event are expecting to see. It's like when you move the Mouse pointer: you can subscribe to the MouseMove event to be notified when this happens; you'll also find details on the pointer position and other details reading the properties provided byMouseEventArgs
. – JimiShowDialog()
. When it is dismissed, you can PULL the info from Form2 using code that is already in Form1 immediately after theShowDialog()
call. Just make a public property in Form2 to access the data. – Idle_Mind