I’m adding an inputbox to my site where I as the admin can enter sql select statements, I put a try catch around the code that executes the select to try and catch syntax errors but even with this my site goes to the “error in application / ” page when there is a syntax error.
I don’t understand what I am doing wrong. I am developing on Asp.net v4.
The code that executes the custom SQL command is as follows;
try
{
//edtSQL.Text = "WHRE Field='Value'"
//The Resulting SQL Command will be incorrect because of incorrect syntax
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable " + edtSQL.Text;
SqlDataSource1.Select(new DataSourceSelectArguments());
}
catch(Exception ex)
{
//Bad Syntax should be caught here, but it is not. This never get called
// even when there is a syntax error.
lblQueryStatus.Text = "Error, can't execute SQL statment";
}
Instead if the label showing the error message, the site gives an error and goes to the default site error page.
The catch in the above code does actually catch the exception. On the exception set the Select Command to something default that is sure to work ie.
And Execute the select. The reason for this is when the page does a post back it tries to execute the select statement that has been set for it and there is not try catch around this(because its in another context) and this is why the server then defaults to the “error in application / ” page.
The code should look like this