问题描述
嗨!非常感谢您在codeproject上有关SQL Server的出色教程.拜托,我需要一些帮助.我是Microsoft Visual Studio 2008中使用ASP.NET编程的新手,页面语言为C#.
我做了一个简单的应用程序来注册无线连接用户.当用户不插入主键(在我的情况下为MAC地址)时,将显示以下错误消息:违反主键约束"aaaaaclients_PK".无法在对象"dbo.clients"中插入重复密钥.重复的键值为(XXXXXXXXX).
该声明已终止.
我知道为什么会显示该消息,但是我想对其进行自定义并放入我自己的消息,因为用户将无法理解那是什么.请帮我解决这个问题.
.aspx页上用于注册客户端(发生错误的位置)的代码(部分)是这样的:
Hi! Thank you very much for your nice tutorials on SQL Server at codeproject. Please, I need some help. 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.
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">
<deleteparameters>
<asp:Parameter Name="MAC" Type="String" />
</deleteparameters>
<insertparameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Surname" Type="String" />
<asp:Parameter Name="MAC" Type="String" />
</insertparameters>
在此先感谢,
弗兰克.
Thanks in Advance,
Frank.
推荐答案
在此先感谢,
弗兰克.
Thanks in Advance,
Frank.
private void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e)
{
var pkValue = e.Command.Parameters["@MAC"].Value;
if(string.IsNullOrEmpty(pkValue))
{
//Show some error message here assuming you've got a Label lblError in your page:
lblError.Text = "You must specify a MAC Address";
//cancels the insert
e.Cancel = true;
}
}
这篇关于ASP.NET中的主键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!