I have a code behind page that has several method; one of them is a page method.
[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
LoadCallHistory(TheNewDate.Date);
}
protected void LoadCallHistory(DateTime TheDate)
{ bunch of stuff }
The method LoadCallHistory works fine when the page loads and I can call it from other methods inside the page. However, in the web method part, it gets underlined in red with the error “an object reference is required for the non-static field”.
How do you access functions from the page method part of the code?
Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You cannot call a non-static method from a static context without having an instance of the class. Either remove static from ResetDate or make LoadCallHistory static.
However, if you remove static from ResetDate you must have an instance of it to use that method. Another approach is to create an instance of the class inside ResetDate and use that instance to call LoadCallHistory, something like this:
[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
var callHistoryHandler = new Pages_CallHistory();
callHistoryHandler.LoadCallHistory(TheNewDate.Date);
}
The error message indicates that ResetDate has the keyword static and LoadCallHistory does not. When using static either both of the methods needs to be static or the called method needs to be static, the caller cannot be static if the called method is not.
To quote MSDN on “Static Classes and Static Class Members”
A static class is basically the same
as a non-static class, but there is
one difference: a static class cannot
be instantiated. In other words, you
cannot use the new keyword to create a
variable of the class type. Because
there is no instance variable, you
access the members of a static class
by using the class name itself.
Method 2
Since this is a static method, it can only call other static methods or new objects.
If your page class is CallHistory (educated guess ;)) you will need to do this:
[WebMethod]
public static void ResetDate(DateTime TheNewDate)
{
var thisPage = new CallHistory();
thisPage.LoadCallHistory(TheNewDate.Date);
}
Or change LoadCallHistory to be static.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0