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.
SELECT * FROM Database
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
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)
{
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable"; //This will work for sure
SqlDataSource1.Select(new DataSourceSelectArguments());
lblQueryStatus.Text = "Error, can't execute SQL statment";
}
2
solved Why does try catch not catch Sql syntax error