View Full Version : How to handle a primary key error in ASP.NET

11-12-2011, 06:50 PM
Hi everybody!

I'm new in programming with ASP.NET in Microsoft Visual Studio 2008, with the page language being C#.

I made a simple application to register wireless connection users. When a user doesn't instert a primar key, in my case a MAC address, the following error msg is displayed: Violation of PRIMARY KEY constraint 'aaaaaclients_PK'. Cannot insert duplicate key in object 'dbo.clients'. The duplicate key value is (XXXXXXXXX).
The statement has been terminated.

I know why the message is displayed, but I want to customize this and put my own message as the user will not understand what that is. Please help me how to handle this. (If there are any codes, please tell me where exactly to insert the codes)

The code (part) of the .aspx page for registering clients(where the error occurs) is this:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:wirelessConnectionString1 %>" InsertCommand="INSERT INTO [clients] ([FirstName], [Surname], [RegNo], [Brand], [MAC], [RegDate], [Expiry], [Remarks]) VALUES (@FirstName,@MAC)"

ProviderName="<%$ ConnectionStrings:wirelessConnectionString1.ProviderName %>"
SelectCommand="SELECT [FirstName], [Surname], [MAC] FROM [clients]"

UpdateCommand="UPDATE [clients] SET [FirstName] = @FirstName, [Surname] = @Surname, WHERE [MAC] = @MAC">


<asp:Parameter Name="MAC" Type="String" />


<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Surname" Type="String" />
<asp:Parameter Name="MAC" Type="String" />


Thanks in advance,

11-17-2011, 11:02 AM
No one to help?

11-17-2011, 10:05 PM
i think it is because (and it probably worked once) if you do not validate for that field and it get sent it get's sent as a string still

string value = "";

and now you try to insert into a table a new PK of a unique value of "" where "" already exists. Check you DB there is probably a PK with value of "" somewhere.

IMO you should not be using a MAC as a PK (even though they are unique); make a TAB_ID column and let SQL handle it's own PK'ing... don't try to mess with it's engine. Also you should validate for blank strings especially if you are banking on it using that string as a PK