Reputation: 1297
Hi all I have 3 forms in the first form I've declared:
public int number1;
then my function sets a value to number1, and when I check the value of number1 from my console it is the value the function gives to it.
than I open my second form and with the second form I go to the 3rd form, Here I want to display the value of number1 and here is the code I use in form3:
private void haberlesme_Load(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
label1.text = frm1.number1.tostring();
}
my function in form1 to set a value to number1 is:
public int setNumber1(string num){
retrun convert.int32(num);
}
inside the button the code is:
number1 = setNumber1(txtValue.text);
messagebox.show("Number1 is : " + number1.toString());
// Here is the other code to open form2..
On a messagebox number1 is display with the assigned value from the textbox But when I click to open form3(haberlesme) Where in the haberlesme_load section the code is: above
It displays 0; what am I missing here?
Upvotes: 0
Views: 77
Reputation: 218877
The default value for an int
is 0
. So when you create a new object:
Form1 frm1 = new Form1();
until something changes that value, it's going to be 0
. You have a couple of options, and it's not entirely clear from the context which is the best design for you.
You could make the variable static so that there's only one in the domain, rather than one per form instance. Something like this:
public static int number1;
Then other forms can access the value from the class rather than the instance:
label1.txt = Form1.number1;
If it genuinely should be an instance variable then you'll need a reference to the actual instance which holds the value you want. Creating a new instance doesn't do that.
(As an analogy... Imagine that your friend has a car and he has something for you in the glove box. If you go out and buy an identical car, that item won't be in the glove box of the new car. It's only in the glove box of that specific car, not in all cars of the same type.)
That would involve passing a reference from one form to another as they're created. For example, if Form2
needs to reference the value then Form2
officially has a dependency on Form1
, so it should require it on its constructor:
private Form1Instance { get; set; }
public Form2(Form1 form1Instance)
{
this.Form1Instance = form1Instance;
}
Then when Form1
creates a new Form2
, it supplies a reference to itself:
var form2 = new Form2(this);
form2.Show();
Then in Form2
you can access that instance:
var theNumber = this.Form1Instance.number1;
If this has to continue to another form, use the same pattern. The third form has a dependency, so it requires the reference when it's created. Whatever form creates it therefore must supply the reference, so it also has a dependency, so it requires the reference when it's created. And so on.
Upvotes: 2