如何将Request.Query字符串转换为整数值。我已经尝试了所有Convert.ToInt32和Int32.Parse,但它说输入字符串的格式不正确。我使用字符串值作为存储过程的输入,该存储过程仅接受该字段的整数类型。
这是代码的一部分 -
string rid=Request.QueryString["RID"];
lblRID.Text = rid;
int id= Int32.Parse(rid);
if (lblRID.Text!= null)
SqlCommand myCommand = new SqlCommand("usp_NewResource_get", myConnection);
myCommand.Parameters.AddWithValue("@RID",id); //RID is int in database and stored procedure
myCommand.CommandType = CommandType.StoredProcedure;
答案 0 :(得分:9)
int foo;
int.TryParse(Request.QueryString["foo"], out foo);
或者就像你说的那样,int.Parse
应该转换为int
你能在这里发布一些代码吗?
答案 1 :(得分:6)
快速和脏(在页面加载中,因为这是一个例子,你应该能够弄清楚发生了什么)
<script runat="server">
private void Page_Load(object sender, System.EventArgs e){
string test = Request.QueryString["foo"];
//Convert the query string you captured to an int and store it in an int.
int intTest = Convert.ToInt32(test);
Response.Write(intTest.GetType() + "<br>" + intTest);
}
</script>
答案 2 :(得分:3)
如何查看您提供给Int32.Parse的输入?
答案 3 :(得分:2)
我们使用每个Page继承的基类。我们有以下方法从querystring params返回整数值:
protected int FetchQueryStringIdentifierByKey(string key)
{
int identifier;
var isInt = int.TryParse(Request.QueryString[key], out identifier);
return (isInt) ? identifier : 0;
}
Credit前往Jayson Knight研究他在.NET 2.0下的原始基准测试结果。
答案 4 :(得分:1)
string id = Request.QueryString["RID"].ToString();
userid=Convert.ToInt32(id);
答案 5 :(得分:0)
如何使用TryParse:
string rid = Request.QueryString["RID"]; int id = 0; if (!string.IsNullOrEmpty(rid) && Int32.TryParse(rid, out id)) { lblRID.Text = rid; SqlCommand myCommand = new SqlCommand("usp_NewResource_get", myConnection); myCommand.Parameters.AddWithValue("@RID",id); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Execute... }
答案 6 :(得分:0)
问题是带有RID参数的查询字符串中传递的值不是数字,因此无法解析为int。例如,你有?RID=hello
或者根本没有RID参数(在这种情况下,值为null)。检查查询字符串以查看传递的实际值。