Reputation: 1916
In my windows form application, I am trying to pass one of the value to another form but when the code reach to another form the value shows as null when I use breakpoints.
In Form1 I have one method that generates the OrderNumber and this order number is being used by Form1 itself as well as Form2. If I called Form1.OrderNumber from Form2 it will generate different order number. I want both Forms should have same order number.
So in Form1 I declare global variable as
public string ord;
Now this "ord" variable gets its value from the following method in Form1.
public string orderNumber()
{
string ord = "ORD" + DateTime.Now.Year + get_next_id();
return ord;
}
where the get_next_id is another method which generates number according to the previous number in database.
Now in form1 itself when I use the "ord" variable value in following code the value comes as null.
InsertUser(maskedTextBox1.Text, comboBox1.Text, maskedTextBox2.Text, maskedTextBox3.Text, maskedTextBox4.Text, maskedTextBox5.Text,
maskedTextBox6.Text, maskedTextBox7.Text, maskedTextBox8.Text, maskedTextBox9.Text, listItems, DateTime.Now, maskedTextBox10.Text, ord, get_next_id());
}
And same happens in form2 as well.
I am not sure where I am wrong. I posted this question before as well but didn't receive any useful answer. Any help please..
To pass the value of "ord" to form2 I am calling this code in form 1.
SaveAllListItems();
//this.Close();
PrintOrder m = new PrintOrder(ord);
m.Show();
where PrintOrder is form2
Upvotes: 0
Views: 1760
Reputation: 101
public static string ord;
Simple used the static keyword. The Advantage of the Static keyword.
Upvotes: 1
Reputation: 2493
That is because in the following code, you are declaring a new local variable called ord.
public string orderNumber()
{
string ord = "ORD" + DateTime.Now.Year + get_next_id();
return ord;
}
To make it work, change the above function to:
public void OrderNumber()
{
ord = "ORD" + DateTime.Now.Year + get_next_id();
}
OrderNumber
does not need to return a value since you will be using ord
anyways.
OrderNumber
needs to be called before you try to retrieve the value for ord
. When you initially declare ord
, the value is null. Calling OrderNumber
will change it's value from null to whatever you like.
Upvotes: 0
Reputation: 223257
Now this "ord" variable gets its value from the following method in Form1.,
Its not, you are defining a local variable again in the method, you r not setting the class level variable in your method.
public string orderNumber()
{
string ord = "ORD" + DateTime.Now.Year + get_next_id();
^^^^^^^^^^
//indicating a local variable, not class level
return ord;
}
Should be:
public string orderNumber()
{
ord = "ORD" + DateTime.Now.Year + get_next_id();
return ord;
}
Upvotes: 2
Reputation: 317
instead of
string ord = "ORD" + DateTime.Now.Year + get_next_id();
use
ord = "ORD" + DateTime.Now.Year + get_next_id();
Upvotes: 0