0

I'm new in C# I have a question. I'm using telerik and I get an error using an object initialized in the Load_page method.

This is my code:

public partial class Test : System.Web.UI.Page {
private Customer customer;

protected void Page_Load(object sender, EventArgs e) {
    if (!Page.IsPostBack){
        customer = new Customer();
        customer.Name = "John";
   }
}

protected void Button_Click(object sender, EventArgs e) {
    MessageBox.Show(customer.Name); //error customer is null
}

}

Why customer is null?

0

2 Answers 2

3

Customer is null, because when the page posts back the Test page instance has to be constructed again, at this point it has no customer.

When Page_Load is called, you suppress creating a customer if it's a postback (that's what the button click does - posts back).

Therefore when you attempt to show the customer's name the customer is null. What you need to do is persist this customer somehow (either in a database, viewstate, transmit to the client and back again).

Also note that you shouldn't show a MessageBox in a web application!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I will store it in session. It is actually the same solution I'd used with other languages. Thank you. p.s. Yes Messagebox was a wrong placeolder.
1

This is because HTTP is stateless protocol. On button click, page will load again and it forget all about customer you intialized previously. You either need to maintain session or put it in page load outside !Page.IsPostBack block

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.