Reputation: 15
I'm working on a program where I let the user add items to a list view. These items are then stored in a list that makes it really easy for me to load the list view on startup using a StreamReader. Now, here's my problem. The user can select an item in the list view and then click a button to show a window that basically shows more information about the item that the user has selected. In order to change, lets say, the name, I want to open yet ANOTHER window where the user can enter the new name which is then changed and saved into the list when pressing a button.
I can easily access the list from the first child by sending an instance of Form1 to Form2 using a constructor. But how do I go about accessing Form1 from Form3 when Form3 is opened from Form2?
I use the following code to access Form1 in Form2:
Form1:
private void button1_Click(object sender, System.EventArgs e)
{
Form2 form2 = new Form2(this);
form2.StartPosition = FormStartPosition.CenterParent;
form2.ShowDialog(this);
}
Form2:
private Form1 _Form1;
public Form2(Form1 _Form1)
{
this._Form1 = _Form1;
}
Upvotes: 0
Views: 40
Reputation: 37030
"how do I go about accessing
Form1
fromForm3
whenForm3
is opened fromForm2
"
Well, since Form2
has access to the instance of Form1
, if Form3
needs it then Form2
can give it.
One way is to pass it through the constructor, as you did previously:
public class Form2
{
private Form1 _Form1;
public Form2(Form1 form1)
{
this._Form1 = form1;
}
// Imaginary method that needs to pass Form1 to Form3
public string GetName()
{
// Pass our reference to Form1 to the constructor of Form3
Form3 form3 = new Form3(this._Form1);
form3.StartPosition = FormStartPosition.CenterParent;
form3.ShowDialog(this);
return form3.txtName.Text;
}
}
Upvotes: 1