Reputation: 25
I have tried the other solutions on stackoverflow like here but I still cannot manage to get this to work. I just want to be able to access the customer object in these two methods, but it is always null in the last method. What am I missing here?
public class Administration_CustomerDisplay : Page
{
private Customer customer;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
customer = new Customer();
customer.Name = "test";
}
protected void Button1_Click(object sender, EventArgs e)
{
Console.WriteLine(customer); //Why is this null ?
}
}
Upvotes: 0
Views: 96
Reputation: 621
You should save the instance in Session
like below.
public partial class Administration_CustomerDisplay : System.Web.UI.Page
{
Customer customer;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
customer = new Customer();
customer.Name = "test";
HttpContext.Current.Session["customer"] = customer;
}
protected void Button1_Click(object sender, EventArgs e)
{
customer = HttpContext.Current.Session["customer"];
Console.WriteLine(customer.Name); //Why is this null ?
}
}
Upvotes: 2
Reputation: 1
Obiviously the cuntomer must be global variable.
public class Administration_CustomerDisplay : Page
{
private Customer customer = new Customer();
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
customer.Name = "test";
}
protected void Button1_Click(object sender, EventArgs e)
{
Console.WriteLine(customer); //Why is this null ?
}
}
Upvotes: 0
Reputation: 54417
Unlike in a Windows application, your Page object doesn't just sit in memory the whole time. That object gets created on the server each time the user makes a request. Each event is going to correspond to a different request and therefore a different Page object. The second object doesn't know anything about the first object and the value of its customer
field. The second object never has its customer
field set so it is always null.
If you want a value to be persisted between requests then you have to use a session variable.
Upvotes: 2
Reputation: 204
The customer object is only created when the droplist changes... then your pages renders after the droplist change and the customer object is gone.
You would need to persist the object in the session if you want it to be available after a button click.
Upvotes: 4