我想将前端的值添加到表中。我想在asp.net中做到这一点。我有一张如下表:-
CategoryId int
CategoryName nvarchar(50) not null
ParentId int null
另请参阅代码:-
<asp:TextBox ID="txtCategory" runat="server"></asp:TextBox>
<asp:Button ID="btnCategoryUpload" runat="server" Text="Upload Category" Width="110" />
我尝试使用这样的代码:-
<form id="form1" runat="server">
<asp:TextBox ID="txtCategory" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="110" OnClick="btnSubmit_Click" />
</form>
相同的代码背后: -
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Insert into CategoriesForMerchant values (@CategoryName, @ParentId)", conn);
cmd.Parameters.AddWithValue("@CategoryName", txtCategory.Text);
cmd.Parameters.AddWithValue("@ParentId", "");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Write("<script>alert('File uploaded successfully');</script>");
}
但我收到以下错误,请帮助。
INSERT 语句与 FOREIGN KEY SAME TABLE 约束“fk_subcategories”冲突。冲突发生在数据库“Test”、表“dbo.CategoriesForMerchant”、列“CategoryId”中。该语句已终止。
请帮忙
表代码:-
create table [dbo].[categories](
id int identity(1,1) not null,
name nvarchar(50) not null,
parent int null,
constraint [pk_categories] primary key clustered ( id asc))
go
alter table [dbo].[categories] with check add constraint [fk_subcategories] foreign key(parent)
references [dbo].[categories] ([id])
go
alter table [dbo].[categories] check constraint [fk_subcategories]
go
在按钮单击时,我必须按照@MarkSinkinson 的建议做这样的事情。