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.
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.
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
.