Click here to Skip to main content
15,896,398 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
When I use object of class it gives exception "Object reference not set to an instance of an object"
my code is
C#
Customer cms=null;
 protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                cms= new Customer();              
              
            }

        }
protected void btnsubmit_Click(object sender, EventArgs e)
        {
cms.GetCode(); //exception is here
}
Posted

It is because you are checking for !IsPostBack. Remember, this is code that executes on the server. So, when the button is clicked your Page_Load first runs but since !IsPostBack is there cms = null because it is defined that way in the class. Then btnSubmit click fires.

Just start cms= new Customer() in btnsubmit.
 
Share this answer
 
Comments
Member 7909353 10-Oct-13 8:34am    
Is it better that assigned memory by this line Customer cms=new Customer(); before page load;
ZurdoDev 10-Oct-13 8:37am    
It all depends on what you are doing. It's important to understand that all code executes on the server and then html is sent to the client. At that point you are totally disconnected so any variables in the page are no more and when they click a button your page is processed new except that it is a postback.
if IsPostBack is not false, then cmd reamins null, hence you get the exception.
 
Share this answer
 
Comments
Member 7909353 10-Oct-13 8:36am    
But first time it is false then I can create object.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900