Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a non-static method and i want to call it in a static webmethod.
I have created an object of that class in static method to call that non-static method.
C#
MyClass obj=new MyClass();
obj.nonStatic();


But its showing exception that object reference not set to instance of object.
Can you help me to call the non-static method in static webmethod.
Posted

1 solution

Sounds like you are using PageMethod to get your data and trying the above thing in that method.

You need to know that, Page Methods cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls. Hence you are unable to access it and get an error.
Have a look here, a good read: Why do ASP.NET AJAX page methods have to be static?[^]


Still, if you really want it then there is a round about way to accomplish it like the following:
C#
// Can call a non-static method through an object reference from within a static method.
public static void staticMeth(MyClass obj) 
{
   // This will not throw an error
   obj.nonStatic(); 
}
 
Share this answer
 
Comments
akee seth 10-May-12 1:33am    
After calling the nonstatic method through object its going to that method.But in that nonstatic method i have to set a label value and exception is shown when the label value is set.
Sandeep Mewara 10-May-12 2:00am    
Sorry, you cannot do that. I already shared the reason why. Your page and control instances does not exist in a PageMethod call. Your server side changes wont take affect.

If you *have* to do this then try AJAX via Webservice instead of Pagemethod. Here: WebService call[^]

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