473,472 Members | 2,139 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

FormView, SqlDataSource and handling exceptions

Rob
Hey all,

So.. a simple FormView/SqlDataSource to handle inserting records into a
table. The table has a primary key that the user enters (eg DiscountCode).
If the user enters a duplicate the database complains about a primary key
violation (which is what I want) and an exception is thrown. The OnInserted
event of the SqlDataSource provides access to the exception so, presumably,
you can provide nice handling for various errors.

For example:

protected void FormView1_ItemInserted(object sender,
FormViewInsertedEventArgs e)
{
//
// If there wasn't an exception the record was added successfully
//
if (e.Exception == null)
{
Response.Clear();
Response.Redirect("HappyLand.aspx");
Response.End();
}

//
// An exception occurred. Handle PK violations only
//
System.Data.SqlClient.SqlException se = e.Exception as
System.Data.SqlClient.SqlException;
if (se != null)
{
if (se.Number == 2627)
{
e.ExceptionHandled = true;
}
}
}

Now... what I can't seem to figure out is a "good" way of actually handling
the error. What I'd like to do is indicate that the page is invalid and have
a validation summary displayed along with a polite error message (ala
"Cannot insert duplicate record!").

However... even if I include a call to Page.Validate() which fires up a
custom validator that "knows" a duplicate record was just inserted.... the
summary does not display and the other controls reset to empty (i.e. the
values the user just entered are lost).

Here's what I mean:

private bool _Duplicate = false;

protected void FormView1_ItemInserted(object sender,
FormViewInsertedEventArgs e)
{
_Duplicate = false;

//
// If there wasn't an exception the record was added successfully
//
if (e.Exception == null)
{
Response.Clear();
Response.Redirect("AdminDiscountsList.aspx");
Response.End();
}

//
// An exception occurred. Handle PK violations only
//
System.Data.SqlClient.SqlException se = e.Exception as
System.Data.SqlClient.SqlException;
if (se != null)
{
if (se.Number == 2627)
{
_Duplicate = true;
Page.Validate();
e.ExceptionHandled = true;
}
}
}

protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = !_Duplicate;
}

So... what is the correct way of handling a PK violation using FormView and
SqlDataSource?

Regards,

Rob
Apr 27 '06 #1
4 13518
What i would do is check for the primary key in the database in the
ItemInserting event handler and then set e.Cancel to true, that way an
excpetion never gets generated and you return to the FormView in inserting
mode with all values maintained. You can also put up some error text in a
label control as well. It probably gives you more overhead than handling the
exception but it is neat and works. An even better way would be to not allow
the user to specify the primary key. In my opinion there are very few good
reasons for allowing this, the only one i can think of off hand is username
in an acl type table.

"Rob" wrote:
Hey all,

So.. a simple FormView/SqlDataSource to handle inserting records into a
table. The table has a primary key that the user enters (eg DiscountCode).
If the user enters a duplicate the database complains about a primary key
violation (which is what I want) and an exception is thrown. The OnInserted
event of the SqlDataSource provides access to the exception so, presumably,
you can provide nice handling for various errors.

For example:

protected void FormView1_ItemInserted(object sender,
FormViewInsertedEventArgs e)
{
//
// If there wasn't an exception the record was added successfully
//
if (e.Exception == null)
{
Response.Clear();
Response.Redirect("HappyLand.aspx");
Response.End();
}

//
// An exception occurred. Handle PK violations only
//
System.Data.SqlClient.SqlException se = e.Exception as
System.Data.SqlClient.SqlException;
if (se != null)
{
if (se.Number == 2627)
{
e.ExceptionHandled = true;
}
}
}

Now... what I can't seem to figure out is a "good" way of actually handling
the error. What I'd like to do is indicate that the page is invalid and have
a validation summary displayed along with a polite error message (ala
"Cannot insert duplicate record!").

However... even if I include a call to Page.Validate() which fires up a
custom validator that "knows" a duplicate record was just inserted.... the
summary does not display and the other controls reset to empty (i.e. the
values the user just entered are lost).

Here's what I mean:

private bool _Duplicate = false;

protected void FormView1_ItemInserted(object sender,
FormViewInsertedEventArgs e)
{
_Duplicate = false;

//
// If there wasn't an exception the record was added successfully
//
if (e.Exception == null)
{
Response.Clear();
Response.Redirect("AdminDiscountsList.aspx");
Response.End();
}

//
// An exception occurred. Handle PK violations only
//
System.Data.SqlClient.SqlException se = e.Exception as
System.Data.SqlClient.SqlException;
if (se != null)
{
if (se.Number == 2627)
{
_Duplicate = true;
Page.Validate();
e.ExceptionHandled = true;
}
}
}

protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = !_Duplicate;
}

So... what is the correct way of handling a PK violation using FormView and
SqlDataSource?

Regards,

Rob

Apr 27 '06 #2
Rob

"clickon" <cl*****@discussions.microsoft.com> wrote in message
news:9A**********************************@microsof t.com...
What i would do is check for the primary key in the database in the
ItemInserting event handler and then set e.Cancel to true, that way an
excpetion never gets generated and you return to the FormView in inserting
mode with all values maintained.


A couple of thoughts on this... checking first will not prevent a PK
violation... between the time the check is done and the time the insert is
done, another user can insert a record. Very unlikely but possible. I'm
hoping for a "perfect" solution (if possible).

Secondly regardless of the advisability of letting users enter primary key
values (which I tend not to allow... just in the instance I goofed) the
business rule is "cannot have duplicate 'code values'". So whether or not
the 'code value' is a PK or not, the database will throw a constraint
violation (uniqueness).

So... I'd still like an actual solution. Though maybe I'll have to hide the
FormView, display a message about a duplicate, and the user can click Back
on the browser. Which I don't like much either... I'd rather have a
consistent mechanism for reporting "validation" problems to a user (ala a
ValidationSummary).

Thanks!

Rob
Apr 27 '06 #3
The way i see it the main rpoblem with catching the exception is that as far
as ASP is concerned the DataInsert has completed, so all the values entered
are lost.

If you do it the way i sugested, check every value that has to be unique
according to your busines rules and catch the exception any way. That way
you will not lose the entered values in almost all circumstances. In the
rare occaision that a duplicate value is inserted in between you checking for
it and the Insert query actually tring to insert it then the exception will
be caught and dealt with but the user will lost the values they entered (very
very unlikely to actually happen).

Alternatively, so long as you are doing the insert in a stored procedure, if
you make the parameters two way (input and output) then you could catch the
exception, flip the FormView back into Insert mode, and manually re-populate
the values of the controls in the form view with the value from the
parameters returned from the stored procedure and also display an error.
This require quite a bit more code than the other method but it should be
more efecient because you are only making one call to the data base
"Rob" wrote:

"clickon" <cl*****@discussions.microsoft.com> wrote in message
news:9A**********************************@microsof t.com...
What i would do is check for the primary key in the database in the
ItemInserting event handler and then set e.Cancel to true, that way an
excpetion never gets generated and you return to the FormView in inserting
mode with all values maintained.


A couple of thoughts on this... checking first will not prevent a PK
violation... between the time the check is done and the time the insert is
done, another user can insert a record. Very unlikely but possible. I'm
hoping for a "perfect" solution (if possible).

Secondly regardless of the advisability of letting users enter primary key
values (which I tend not to allow... just in the instance I goofed) the
business rule is "cannot have duplicate 'code values'". So whether or not
the 'code value' is a PK or not, the database will throw a constraint
violation (uniqueness).

So... I'd still like an actual solution. Though maybe I'll have to hide the
FormView, display a message about a duplicate, and the user can click Back
on the browser. Which I don't like much either... I'd rather have a
consistent mechanism for reporting "validation" problems to a user (ala a
ValidationSummary).

Thanks!

Rob

Apr 27 '06 #4
Rob
> almost all circumstances. In the rare occaision
(very very unlikely to actually happen).


hehehe... famous last words ;)

I will likely do a validation check for duplicates and handle the exception
by displaying a "oops duplicate record, click back and correct" label
instead of the formview.

I guess I was hoping that because the formview/sqldatasource makes the
exception available, and has a HandledException flag, that there would be a
way to treat the exception as a validation error and represent the same
information. I guess I don't see that as a stretch... treat exception like a
validation error... seems like a likely enough approach.

In otherwords allow an application to gracefully handle database constraint
exceptions (eg. consistant ui/error messaging) when using a
formview/sqldatasource.

Regards,

Rob
Apr 27 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Ottar | last post by:
I have a few numeric fields, and when I update i get the error: "Input string was not in a correct format". Next line:" System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&...
3
by: sck10 | last post by:
Hello, I am creating a form for users to enter information about a lab and the members of the lab. I have one form (FormView) that they use to enter information about that lab. The keyvalue is...
0
by: Metal2You | last post by:
I'm working on an ASP.NET 2.0 application in Visual Studio 2005 that accesses a Sybase database back end. We're using Sybase SQL Anywhere 9.0.2.3228. I have installed and registered the Sybase...
7
by: Lorenzino | last post by:
Hi, I have a problem with bindings in a formview. I have a formview; in the insert template i've created a wizard control and inside it i have an HTML table with some textboxes bound to the...
1
by: | last post by:
Is there a way to handle when you're on insert mode on a formview and the record you're about to save to the database already exist and insted you rather update instead of inserting and getting an...
2
by: Ned Balzer | last post by:
I'm trying to create a formview bound to a sqldatasource, and use a stored procedure to insert data from the formview into several tables. I have some simplified code below, the real code is much...
4
by: J055 | last post by:
Hi I have 2 update buttons in my FormView ('Apply' and 'OK'). I want both buttons to update the data source but the 'OK' button should redirect afterwards. I can see which button is clicked...
3
by: YMPN | last post by:
Hi Everyone, I'm deen from Riyadh. Please do help me with some problem i have. I have this formview control setup to recieved inputs from user (textbox, dropdownlist, others). After...
0
by: LiamLiamLiam | last post by:
G'day all. I having a problem with my formview. I'll ty to explain my situation as best as i can. I have a page with a search field at the top which is just a simple asp:textbox. Below that i...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.