Loading ...

Delete a record from database using ADO.NET | CodeAsp.Net

Delete a record from database using ADO.NET

 /5
0 (0votes)

In this blog i will show how to delete a record from database using ADO.NET. I have used one text box and one button, user will enter id and click submit button, accordingly row will be deleted from database.

Here is the code

In Sql

CREATE TABLE [Test_Table]

([ID] INT IDENTITY ,[NAME] VARCHAR(20) )

GO

INSERT INTO [Test_Table]

SELECT 'NAME1'

UNION ALL

SELECT 'NAME2'

UNION ALL

SELECT 'NAME3'

GO

CREATE PROC DELETE_Test_Table
@ID INT
AS

BEGIN
    DELETE FROM [Test_Table] WHERE ID=@ID
END





In ASPX:


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form runat="server">
    <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
    <asp:Button ID="btnDelete" runat="server" Text="Submit"
        onclick="btnDelete_Click" />
    </form>
</body>
</html>




In Codebehind:
using System;
using System.Data;
using System.Data.SqlClient;

namespace TestProject
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
           

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
           
            using (SqlConnection connection = new SqlConnection("xxxxxxxxxx—-Your Connection String—xxxxx"))
            {

                using (SqlCommand command = new SqlCommand("DELETE_Test_Table", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    SqlParameter paramID = new SqlParameter("ID", Convert.ToInt32(txtID.Text))
                                               {SqlDbType = SqlDbType.Int};
                   
                    command.Parameters.Add(paramID);

                    connection.Open();
                    command.ExecuteNonQuery();

                   

                }

            }
        }

    }
}





Do let me know your feedback, comments.

Comments (no comments yet)

Top Posts