Catching a Constraint Exception

G

Guest

I am creating a "setup" page that allows users to fill out various tables of
key,value pairs that are basically the table for foreign keys within a master
table. It all works very well, but when a user tries to delete a record that
is currently being used in the master table the SQLServer obviously won't let
you because of the contraint on hte foreign key and ASP.net throws and
exception. What is the best way to catch this exception, perhaps in the
deleting event of the gridview control that i am using for editing/deleting
data in the table.
 
F

Flinky Wisty Pomm

There's an example of handling SqlDataSource exceptions here
http://fredrik.nsquared2.com/viewpost.aspx?PostID=300 courtesy of the
ever-helpful Fredrik Norméns.

ObjectDataSources work in the same way.

If you want much more control than that, you're getting into murky
waters. Personally, I'd return an error code from my stored proc and
throw a custom exception in the data layer.
 
G

Guest

Thanks that's very helpfull.

To get som ething going i have written the following code

protected void sdsComplaintStatus_Deleted(object sender,
SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
e.ExceptionHandled = true;
lblNoDelete.Text = "Cannot delete, value in use";
lblNoDelete.ForeColor = System.Drawing.Color.Red;
}

}

On the basis that the only exception likely to be thrown is the user is
trying to delete a record that is in use as a foreign key in another table,
and i can make it more sophisticated once i have this up and running. Thing
is it still thorws the exception. Any ideas ?

I have written code to check for the condition before attempting the delete,
but it is a bit complex and this way would be more elegant.
 
F

Flinky Wisty Pomm

Heh... I did mean to ask "did you wire the event up?" but ... Glad it
works for you.
 
G

Guest

Yeah i did wire the event up, but then saved the codebehind page and forgot
to save the aspx page. Doh!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top