Reputation: 8404
I've got the following code:
namespace CST
{
public partial class frmBenefitSummaryList : System.Web.UI.Page
{
public string PlanID = Convert.ToString(Request.QueryString["PlanID"]);
public string AuditID = Convert.ToString(Request.QueryString["AuditID"]);
protected void Page_Load(object sender, EventArgs e)
{
this.MaintainScrollPositionOnPostBack = true;
BindAccordions();
if (!Page.IsPostBack)
{
LoadIssues();
LoadResolutions();
LoadNetworks();
LoadStatus();
}
}
etc...
What I need to do is use PlanID and AuditID in other parts of my code. However, when I try to make them public (as I have in the above code), I get an error:
A field initializer cannot reference the non-static field, method or property 'Page.Request'
Any idea how to make those variables global?
For the record, I'm opening this page from another page using
String SUrl = "frmSummary.aspx?PlanID=" + PlanID + "&AuditID=" + AuditID;
Server.Transfer(SUrl, true);
Upvotes: 1
Views: 724
Reputation: 62238
... I have to filter some data based on a user's input, and bind that data to a grid. In order to get the user's selection into 'BindAccordions()'...
Change your signature of BindAccordions()
to BindAccordions(int planId, int auditId)
and then pass them in when you call the method
protected void Page_Load(object sender, EventArgs e)
{
// note there is a null/empty check on the query string parameters and a default of 0 will be used if no value is included
// it does not protect against unexpected values like "ABC"
// if 0 is encountered and its not expected then you can return an error message or something else
var planId = string.IsNullOrWhiteSpace(Request.QueryString["PlanID"])
? 0
: int.Parse(Request.QueryString["PlanID"]);
var auditId = string.IsNullOrWhiteSpace(Request.QueryString["AuditID"])
? 0
: int.Parse(Request.QueryString["AuditID"]);
if (!Page.IsPostBack) {
// existing code before left unchanged ...
BindAccordions(planId, auditId);
// existing code after left unchanged ...
}
The underlying reason for the Exception as pointed out in @B2K
's answer is that you were trying to use class level property in your property initializer but this is not allowed because there is no guarantee that the property (Request) itself has been initialized yet when your initializer runs.
Best practice though is to limit scope whenever possible, so in this case passing in values into your methods is considered best practice as it limit the scope of those variables.
Upvotes: 3
Reputation: 2611
The problem is that you are referencing the Request object before it is getting set. Try this instead:
public partial class frmBenefitSummaryList : System.Web.UI.Page
{
private string PlanID;
private string AuditID;
protected void Page_Load(object sender, EventArgs e)
{
PlanID = Request["PlanID"];
AuditID = Request["AuditID"];
this.MaintainScrollPositionOnPostBack = true;
BindAccordions();
if (!Page.IsPostBack)
{
LoadIssues();
LoadResolutions();
LoadNetworks();
LoadStatus();
}
}
Upvotes: 1