Convert Request.QueryString to an integer

How to convert a Request.Query string to an integer value. I tried all of Convert.ToInt32 and Int32.Parse, but it says the input line is not in the correct format. I use a string value as an input to a stored procedure that accepts only integer types for this field.

Here's the piece of code -

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;
+3
source share
7 answers
int foo;
int.TryParse(Request.Querystring["foo"], out foo);

or, as you say, int.Parseshould convert it

Could you post some code here?

+8
source

Fast and dirty (and in page loading, because this is an example, you should be able to figure out what comes from this)

<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>
+6
source

, Int32.Parse?

+3

, . , querystring:

protected int FetchQueryStringIdentifierByKey(string key)
{
    int identifier;
    var isInt = int.TryParse(Request.QueryString[key], out identifier);
    return (isInt) ? identifier : 0;
}

Jayson Knight .NET 2.0.

+1
string id = Request.QueryString["RID"].ToString(); 
userid=Convert.ToInt32(id);
+1

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 ...
}
0
source

The problem is that the value passed in the query string with the RID parameter is not a number, so it cannot be parsed using int. For example, you have, ?RID=helloor possibly have no RID parameter at all (in this case, the value is null). Examine the query to see the actual value passed.

0
source

Source: https://habr.com/ru/post/1703222/


All Articles