Tuesday, February 14, 2012

catch sql command if value doesnt exist

I have a sql command that is loaded on page load that collects information based on the query string. The query string is a random group of numbers and letters. How do I catch it and direct to an error page if the query can not be found in the database?

Thanks!

if you are trying to get some parameters from the querystring then you can use

dim queryvariable as string =request.querystring("variable")

try

dim sqlquery as string

sqlquery="SELECT column_Name from Table_name where variable= "& queryvariable

//use this sqlquery to check whether it returns some rows or not

catch

response.redirect("pageNotFound.aspx")

end try

|||

I'm pretty sure i did all that.

in page load i'm doing

getUserInfo(Request.QueryString["uid"]);

then the method

protected void getUserInfo(string userid) {string selectCmd ="SELECT * from users WHERE ID = @.id";string strConnection = ConfigurationManager.ConnectionStrings["TimeAccountingConnectionString"].ConnectionString; SqlConnection myConnection =new SqlConnection(strConnection); SqlCommand myCommand =new SqlCommand(selectCmd, myConnection); myCommand.Parameters.Add(new SqlParameter("@.id", SqlDbType.VarChar, 10)); myCommand.Parameters["@.id"].Value = userid;try { myConnection.Open(); SqlDataReader datareader = myCommand.ExecuteReader();while (datareader.Read()) { lblFirstName.Text = datareader["firstname"].ToString(); lblLastName.Text = datareader["lastname"].ToString(); lblTeam.Text = datareader["team"].ToString(); lblOffice.Text = datareader["office"].ToString(); } datareader.Close(); myConnection.Close(); }catch { Response.Redirect("~/error.aspx"); }
|||

any ideas?

|||

In your code you aren't checking if the datareader actually contains any data or not, so if no records are being returned nothing happens. 1 simple way to do it is:

1. Declare a boolean variable at the top initialized to False: boolean bolUserFound = False

2. Inside the while loop set the value to true: bolUserFound = True

3. After you close the connection evaluate the variable and if it's still false you know no records were found and you need to redirect to your error page:

if (bolUserFound = False) {

Response.Redirect("~/error.aspx");

}

|||

perfect!

Exactly what i needed...

No comments:

Post a Comment