I\'m trying to pass a value set in my parent form to a second form. I created a property with a get part in the parent form.
I don\'t want to do something like:
See this example.
1-Create a window form application,Declare a public string global variable in Form1 , using this variable we can pass value from Form1 to Form2.
2-Now in form2 ,Create a object for Form1 and Get the value using this object.
See image
You have some possibilities here:
Give a Reference from your first Form as value
Form2 secondForm = new Form2(yourForm1);
So you can access via the getter in your first Form. yourForm1.MyValue;
This seems to be a bit ugly. Better is you create a Interface, which hold your Property and is implemented from you first Form.
public interface IValueHolder
{
public int MyValue {get;}
}
public class FirstForm : Form, IValueHolder
{
public int MyValue{get;}
//Do your form stuff
Form2 form = new Form2(this);
}
So your Form2 just take the Interface and stays independent from Form1. Further you can create a Property on Form2 which you access from Form1. For example if your Property in Form1 changes you set the value from Form2 as well.
public class Form2 : Form
{
public int MyValue{get;set;}
}
public class Form1 : Form
{
private int _myValue;
public int MyValue
{
set
{
if (_myValue != value)
{
form2.MyValue = value;
}
}
}
}
At least you can use a Event maybe. Further you can create a Property on Form2 which holds an Form1 Reference or a IValueHolder as described above.
Hope this helps.
I'm not sure about how you are going to use the Form2
in the parent(let it be frmParent
). anyway you can follow any of the steps below:
Define the property in the child form as static so that you can access that by using Form2.frmProperty
.
Or define the property as public and then access through the class instance, so that you can access the variable through that instance as long as the instance existed. something like the following:
Form2 secondFormInstance = new Form2();
secondFormInstance.frmProperty = 10;
// at some later points
int childValue = secondFormInstance.frmProperty; // take value from that variable
secondFormInstance.frmProperty++; // update the value
Or you can use like what you specified in the question.