重複の可能性:
StringをIntに変換するにはどうすればよいですか?
queryString値を(int)に変更するにはどうすればよいですか?
string str_id;
str_id = Request.QueryString["id"];
int id = (int)str_id;
重複の可能性:
StringをIntに変換するにはどうすればよいですか?
queryString値を(int)に変更するにはどうすればよいですか?
string str_id;
str_id = Request.QueryString["id"];
int id = (int)str_id;
Int32.TryParseメソッドを使用して、int
値を安全に取得します。
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
}
これと交換してください
string str_id;
str_id = Request.QueryString["id"];
int id = Convert.ToInt32(str_id);
または単純かつより効率的なもの
string str_id;
str_id = Request.QueryString["id"];
int id = int.Parse(str_id);
あなたがそれをすることができるいくつかの方法があります
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
その他
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
int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);
あなたが使用する必要がありますint.Parse(str_id)
編集 :ユーザー入力を信頼しない
解析する前に、入力が数値であるかどうかを確認することをお勧めします。この場合は、int.TryParseを使用します。