Sql-server – Insert values in table from front-end CategoryId

csql servertable

I want to add a value from front end into a table. I want to do it in asp.net. I have a table which is as below:-

CategoryId     int          
CategoryName   nvarchar(50)   not null
ParentId       int            null

Also see the code:-

<asp:TextBox ID="txtCategory" runat="server"></asp:TextBox>

<asp:Button ID="btnCategoryUpload" runat="server" Text="Upload Category" Width="110" />

I tried with my code like this:-

<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>

Code behind for the same:-

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>");
}

But I got the below error, please help.

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE
constraint "fk_subcategories". The conflict occurred in database
"Test", table "dbo.CategoriesForMerchant", column 'CategoryId'. The
statement has been terminated.

Please help

Table code:-

 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

Best Answer

On Button Click, I got to do something like this, as suggested by @MarkSinkinson.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("Insert into CategoriesForMerchant (CategoryName) values (@CategoryName)", conn);
    cmd.Parameters.AddWithValue("@CategoryName", txtCategory.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
    Response.Write("<script>alert('File uploaded successfully');</script>");
}