Reputation: 534
I have a main form where I'm assigning some variables and passing them to myclass.cs. I need to use class variables in myclass.cs as I need to utilize these variables in several places of that class.
I can see the variables correctly in the CustomerParams method of myclass.cs so I know they're getting there. However, they always return as null if I call them right after the InitializeComponent(); of myclass.cs. If I call them in another event handler such as with a button click in myclass.cs then they always return the first variable assigned and never get updated as I select different ones from the listbox in mainform (even thought he CustomerParams method continues to update as expected). What am I doing wrong?
mainform.cs
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox != null)
{
string customerName = (listBox.SelectedItem.ToString());
MyClass mc = new MyClass();
contentPanel.Controls.Add(mc);
mc.CustomerParams(customerName, customerId);
}
}
myclass.cs
public partial class MyClass : UserControl
{
private int _customerId { get; set; }
private string _customerName {get; set;}
public MyClass()
{
InitializeComponent();
// Shows null values!
Console.WriteLine("Values: " + _customerName + "(" + _customerId + ")");
}
public void CustomerParams(string customerName, int customerId)
{
_customerName = customerName;
_customerId = customerId;
// Shows correct values!
Console.WriteLine("Values-Method: " + _customerName + "(" + _customerId + ")");
}
private void testButton_Click(object sender, EventArgs e)
{
// Only shows the initial value even when the SelectedIndex in mainform.cs changes
Console.WriteLine("Values-Button: " + _customerName + "(" + _customerId + ")");
}
}
Upvotes: 0
Views: 3408
Reputation: 1
I'm just learning c# (coming from C++) and I ran into this same issue. The solution is to declare the class variables STATIC. I guess since the class is never instantiated, the variables need to be static. Explained here:
https://msdn.microsoft.com/en-us/library/79b3xss3.aspx#Anchor_0
Upvotes: 0
Reputation: 534
Fixed the problem. What I ended up doing was in my main form I created a static method where I assign the variables, then call that static method for my button click as well as in myclass where I then assign to variables.
Upvotes: 0
Reputation: 1195
You are getting null after InitializeComponent() because nothing has been assigned to the variables. They have a value in CustomerParams, because you are setting them to the parameters that come through the method. The only place you are assigning values to these variables is in the CustomerParams method, so they will never change value outside of that method.
Upvotes: 2