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.
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.
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
}
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
}
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"];
You can do like this:
string ID = Request.QueryString["ID"].ToString();
int id=int.Parse(ID);
or
int id=Convert.ToInt16(ID);
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.