0

I am currently using the following script to set this value as a String:

string ID = Request.QueryString["ID"].ToString();

However, I'd now like to store it as an Integer.

How do I do this?

Many thanks for any pointers.

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

7 Answers7

5

Assuming you don't want to throw a server error on a bad string

int id=0;
if (int.TryParse(Request.QueryString["ID"],out id)) {
  .. logic for valid id
} else {
  .. logic for invalid id
}
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • You don't need the `ToString()`, the `QueryString` property already returns indexed values as strings. – Quick Joe Smith Mar 22 '12 at 10:22
  • 1
    @QuickJoeSmith Doh, was on automatic I meant to remove that. Now updated – Bob Vale Mar 22 '12 at 10:25
  • For all I know, redundant call is probably optimised away anyway. – Quick Joe Smith Mar 22 '12 at 10:26
  • You don't really need the .QueryString part either, you can just do Request["ID"], although using the Request.QueryString is a bit more readable – JCherryhomes Mar 22 '12 at 12:26
  • Bear in mind that `Request[key]` will search server variables, cookies and form fields as well as the query string. There are plenty of situations in which where a value comes from is just as important as what its value is. – Quick Joe Smith Mar 22 '12 at 21:18
3
int ID = int.Parse(Request.QueryString["ID"].ToString());
gdoron
  • 147,333
  • 58
  • 291
  • 367
daryal
  • 14,643
  • 4
  • 38
  • 54
2

Use either of these:

If you know that you have an ID:

string ID = Request.QueryString["ID"];
int integerId = int.Parse(ID);

or, if the query string may be missing or invalid (never trust query strings....)

string ID = Request.QueryString["ID"];
int integerId;
if (int.TryParse(ID, out integerId))
{
   // you have a valid integer ID here.
   // process it
}
else
{
    // handle missing or invalid ID
}
Neil Moss
  • 6,598
  • 2
  • 26
  • 42
1

You could do something like:

int i = Convert.ToInt32(ID);

or

int i;
Int32.TryParse(ID, out i);

BTW Request.QueryString["ID"] is already a string so the following is fine:

string ID = Request.QueryString["ID"];
Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
0

Try

int ID = int.Parse(Request.QueryString["ID"]);

See How can I convert String to Int?

Community
  • 1
  • 1
Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
0

You can do like this:

string ID = Request.QueryString["ID"].ToString();

int id=int.Parse(ID);

or

int id=Convert.ToInt16(ID);
gdoron
  • 147,333
  • 58
  • 291
  • 367
ankit rajput
  • 182
  • 2
  • 5
0

Always use tryparse for querystring values if you want to convert it to integer even if you never set it to string , because user can change that anytime before sending request (visible in URL).

int id = 0 ;//default value

bool success = int.TryParse(Request.QueryString["ID"],out id))

if (success) { //write code for default value action return; }

//write code for other values.

Imran Rizvi
  • 7,331
  • 11
  • 57
  • 101