Catching SqlDataSource Exception in C#

ASP.NET Comments Off on Catching SqlDataSource Exception in C#

All right, here is a simple tip to catch sqldatasource exception for delete, update, insert, select when using with gridview, dataview, formview, detailsview. If we were coding using 3-tier architecture, the exception can be caught easily using try catch and finally.

The exception can arise when you try to insert duplicate primary key values or delete a record that has child records.

For example if you are using GridView with SqlDataSource to delete a record and if the record has child records then the SqlDataSource and GridView will through an exception in the Deleted Event. We can catch exception and handle the exception as below.

protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
 if (e.Exception != null)
 e.ExceptionHandled = true; //handling the exception

 Label1.Text = "Page Delete Failed";

It is important to set the e.ExceptionHandled to true. Else you will still get the error. This exception can be used either in SqlDataSource Deleted event or GridView Row Deleted Event. The same approach can be used of Insert, Update, Select Events.



Back to Top