Hi smile,
Check this example. Now please take its reference and correct your code.
HTML
<asp:TextBox runat="server" ID="txtStoreID" />
<asp:Button Text="Delete" runat="server" OnClick="OnDelete" />
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void OnDelete(object sender, EventArgs e)
{
string isExist = "";
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT COUNT(*) FROM tblStore WHERE StoreTypeID = @Id";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Id", txtStoreID.Text.Trim());
con.Open();
isExist = Convert.ToString(cmd.ExecuteScalar());
con.Close();
}
}
if (!string.IsNullOrEmpty(isExist))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('First delete record from child table then delete record from the parent table.')", true);
}
else
{
query = "DELETE FROM tblStoreType WHERE StoreTypeID = @Id";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Id", txtStoreID.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
VB.Net
Protected Sub OnDelete(ByVal sender As Object, ByVal e As EventArgs)
Dim isExist As String = ""
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT COUNT(*) FROM tblStore WHERE StoreTypeID = @Id"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.AddWithValue("@Id", txtStoreID.Text.Trim())
con.Open()
isExist = Convert.ToString(cmd.ExecuteScalar())
con.Close()
End Using
End Using
If Not String.IsNullOrEmpty(isExist) Then
ClientScript.RegisterClientScriptBlock(Me.GetType(), "", "alert('First delete record from child table then delete record from the parent table.')", True)
Else
query = "DELETE FROM tblStoreType WHERE StoreTypeID = @Id"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.AddWithValue("@Id", txtStoreID.Text.Trim())
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End If
End Sub