user3266908 user3266908 - 1 month ago 15
ASP.NET (C#) Question

SQL command will not redirect

I created this slice of code but not behaving the way that it should.

What should happen is when the query returns a matching value in the database, it should redirect the page. But no matter what I do, it always returns the value as false, and never redirects correctly.

At least that what I think is going on, any help would be great..

I've been working on this for 3 days and I'm about to lose my mind. If there is a better way of doing this I am all ears.

var SuserId = User.Identity.GetUserId();

SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;

conn.Open();
cmd.CommandText = "select Count(ID) from AspNetStripeUsers where ID=@ID";
cmd.Parameters.AddWithValue("@ID", SuserId);

int result = (int)cmd.ExecuteScalar();

string wewe = result.ToString();

if (wewe == SuserId)
{
Response.Redirect("~/Services/MS/OT/igive");
}

Answer

This int result = (int)cmd.ExecuteScalar(); will always returns a int value which is not be similar to the userID because it will retrieve the first value from Database so just check whether it has any value which means your condition is true

so the above code which is given by Nayan is true.

if (result>0)
{
    Response.Redirect("~/Services/MS/OT/igive");
}
else
{
Console.Writeline("The user id is not valid";

}
Comments