Link to home
Start Free TrialLog in
Avatar of russomr
russomr

asked on

Retrieving and integer querystring value

I am using ASP.Net 1.1 C#.  I have the following line at the top of my code before my functions:

public int recID = Request.QueryString["recid"];

I am getting this error on the above line:

CS0120: An object reference is required for the nonstatic field, method, or property 'System.Web.UI.UserControl.Request.get'

What's going on here?  I'm trying all kinds of different things but can't seem to populate an integer variable with the querystring value.

I've also tried:
public int recID = (int) Request.QueryString["recid"];
static int recID = Request.QueryString["recid"];
public static int recID = Request.QueryString["recid"];

help.


Avatar of apb2
apb2
Flag of United Kingdom of Great Britain and Northern Ireland image

How about:

int recID = (int) Request.QueryString["recid"];

why do you want to give it a public declaration?

If you want to be able to access it publicly i would wite a public property to do so, then you also be following basic oop principles

apb2
forgive my c# (if it's wrong)

int recID = (int) Request.QueryString["recid"];

public int RECID
{
  get
   {
      return recID;
   }
}

hth apb2
Avatar of naveenkohli
naveenkohli

public int recID = (Int32)HttpContext.Current.Request.QueryString["recid"];

But this kind of implementation can get you in trouble. You are assuming that recid QS parametter will always be present in URL. If for some reason you don't have it, this line of code will throw exception.

Move initialization of this variable in Page_Load on OnInit event handler.
Avatar of russomr

ASKER

Nothing seems to be working.  I agree, I should (and did) move it to within the Page_Load event, however I'm getting:

Cannot implicitly convert type 'string' to 'int'


Right now, the path I'm taking is:

int recID = (Int32)HttpContext.Current.Request.QueryString["recid"];

And I am passing a number into the page via querystring.
My fault.. forgot QS come as string

int recID = Int32.Parse(HttpContext.Current.Request.QueryString["recid"]);
Avatar of russomr

ASKER

That seems to work, however you mentioned earlier that it will throw and exception if no parameter is passed, which it does.

In my code, I want to execute a function if the variable recID contains a value, otherwise I want to skip execution of that function.  What is the most efficient way to do this?

I want to do something like this:

// IF RECID VALUE IS PASSED TO PAGE, DISPLAY DEFAULT DATA
if(recID.ToString() != "") {
      if(!IsPostBack) {
            PopulateForm(recID);
      }
}

But getting that exception obviously causes problems.

I've upped the points considering this is a somewhat different question.
ASKER CERTIFIED SOLUTION
Avatar of naveenkohli
naveenkohli

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial