Powered by Blogger.

Thursday, September 26, 2013

Delete record using enterprise library in Asp.Net



In this article we will discuss how to delete a record using enterprise library in Asp.Net.

You should read how to use enterprise library in Asp.Net before starting this article.

You can also check my previous posts on How to convert ArrayList to String using C#? [Click here], Set default focus in Asp.net and Method Overloading in C#.Net.

In this post we will see, whenever a user put an id in the textbox and click on submit, the data should get deleted from the database. Below is the full code:

Store Procedure:

CREATE PROCEDURE DeleteEmployeData
@Empid int
AS
BEGIN

DELETE FROM EmloyeeDetail WHERE Empid=@Empid

END
GO

.aspx code:

<table>
            <tr>
                <td>
                    Emp Id
                </td>
                <td>
                    <asp:TextBox ID="txtEmpid" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
                </td>
            </tr>
            <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>
        </table>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data;

public partial class DeleteData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Database db = DatabaseFactory.CreateDatabase("connection");
        DbCommand dbCommand = db.GetStoredProcCommand("[DeleteEmployeData]");
        db.AddInParameter(dbCommand, "@Empid", DbType.Int32, Convert.ToInt32(txtEmpid.Text));

        try
        {
            int result = db.ExecuteNonQuery(dbCommand);
            if (result > 0)
            {
                lblResult.Text = "Record deleted successfully!";
            }
            else
            {
                lblResult.Text = "Some error occured!";
            }
        }
        catch (Exception ex)
        {          
        }
    }    
}





0 comments

Post a Comment