Reputation: 53
I have a program that needs a data from another form and I need to pass it without creating a new instance of the first form. how can i do that?
ex.
Form2 f2 = new Form2();
f2.showdialog();
when f2 shows, their is an listview with items, when I click on an item, I want the item to be sent back to the first form without closing form2 and without instantiating a new Form1.
Upvotes: 2
Views: 1841
Reputation: 2798
Probably the easiest way is to have a publicly accessible method in Form1
that knows how to handle a new item. Then in Form2
have a reference to the Form2
object. Either Form2
has a Property for that or you set Form1
as parent Form2 f2 = new Form2(f1)
(or this
if you call it from f1).
Now that you have a reference to the Form1
object, you can call its method to handle the item.
Upvotes: 0
Reputation: 3069
You are looking for some kind of event.
public event EventHandler MyButtonClicked;
And before you use ShowDialog();
Form2 f2 = new Form2();
f2.MyButtonClicked += f2_MyButtonClicked;
f2.showdialog();
And somewhere to handle the event
void f2_MyButtonClicked(object sender, EventArgs e)
{
//Here you want to grab your list. You can get f2 from sender.
Form2 f2 = (Form2)sender;
throw new NotImplementedException();
}
When you in Form2 click the button you raise the event.
void myButtonClicked(object sender, EventArgs e)
{
if (MyButtonClicked != null)
{
MyButtonClicked(this, new EventArgs());
}
}
If you want to read more on events have a look at.
http://msdn.microsoft.com/en-us/library/aa645739%28v=vs.71%29.aspx
Upvotes: 1
Reputation: 27356
Perhaps create a mutator(set) method in form1. When you wish to pass data back to form1, call the mutator method to update the form.
Upvotes: 0
Reputation: 223402
I need to pass it without creating a new instance of the first form.
That means you have your first Form open in the background. You can use Application.OpenForms
property to get the already open form and then get the data from there.
Something like:
Form2 f2 = Application.OpenForms["Form2"] as Form2;
if(f2 != null)
string data = f2.SomeProperty;
Upvotes: 1