Reputation: 2554
Currently, I'm receiving the error "an object reference is required for the nonstatic field method or property". My code is as follows:
using MyApp.Global;
namespace MyApp.MyNamespace
{
public class MyClass:System.Web.UI.Page
{
//Toolbox is inside Global, GetCurrentCookieData is a static method
private CookieData cd = Toolbox.GetCurrentCookieData(HttpContext.Current);
//the above was changed and resolved the first error, but another error
//just popped up. Below, I get the error: cd denotes field
//where class was expected
private int CompanyID = Util.GetCompanyIDByUser(cd.Users);
protected override void OnLoad(EventArgs e)
{
//snip
}
protected void MyEventHandler(object sender, EventArgs e)
{
//snip
}
}
}
Currently, each of my methods needs to use cd, so instead of creating a variable inside each method, I was looking for a way to declare it in the class and have it available to all methods. When I try to set cd inside of the methods, it works fine. I've googled around, and it seems that I would have to have an instance of Page in order to use there, but that doesn't work. So I'm really misunderstanding how this works. Can anyone point me in the right direction?
Edit: I added static keyword to cd, in order to resolve the 'cd denotes field where class was expected' error. Is this good implementation?
Edit: I'm going to just mark the correct answer below and ask a new question, as I think it's deserving.
Upvotes: 0
Views: 7698
Reputation: 15663
Protip: Wrap that cookie in a protected property:
protected CookieData CurrentCookie
{
get { return HttpContext.Current.CookieData; }
}
Then all your methods can reference that on the page. I'd suspect what you probably want to do is wrap a specific cookie's value in a property and pass that around.
Upvotes: 1
Reputation: 164341
Use HttpContext.Current as already suggested.
For the rest of your question: Try if you can create the cd field in OnInit, and use it afterwards in your OnLoad and other methods. Your problem is propably that the HttpContext is not yet available when the Page object is being constructed. (See the ASP .NET Page Life Cycle)
Upvotes: 1