4

Possible Duplicate:
How can I convert String to Int?

how can i change queryString value to an (int)

string str_id;
str_id = Request.QueryString["id"];
int id = (int)str_id;
Community
  • 1
  • 1
Hammam Muhareb
  • 355
  • 1
  • 4
  • 11

5 Answers5

10

Use Int32.TryParse Method to get int value safely:

int id;
string str_id = Request.QueryString["id"];
if(int.TryParse(str_id,out id))
{
    //id now contains your int value
}
else
{
    //str_id contained something else, i.e. not int
}
horgh
  • 17,918
  • 22
  • 68
  • 123
3

replace with this one

string str_id;
str_id = Request.QueryString["id"];
int id = Convert.ToInt32(str_id);

or simply and more efficient one

string str_id;
str_id = Request.QueryString["id"];
int id = int.Parse(str_id);
Murali N
  • 3,451
  • 4
  • 27
  • 38
2
int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);
Anthony Faull
  • 17,549
  • 5
  • 55
  • 73
2

There are several ways you can do that

string str_id = Request.QueryString["id"];

int id = 0;

//this prevent exception being thrown in case query string value is not a valid integer
Int32.TryParse(str_id, out id); //returns true if str_id is a valid integer and set the value of id to the value. False otherwise and id remains zero

Others

int id = Int32.Parse(str_id); //will throw exception if string is not valid integer
int id = Convert.ToInt32(str_id);  //will throw exception if string is not valid integer
codingbiz
  • 26,179
  • 8
  • 59
  • 96
1

you have to use int.Parse(str_id)

Edit : don't trust user input

it's better to check if the input is a number or not before parsing , for this use int.TryParse

Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59