How to delete records from ListView in ASP.Net?

Introduction:

In this article i will explain how to Delete ListView records.

Description:

In previous articles i explained How to bind data to ListView controlHow to Insert new record from ListView Footer (or) How to use InsertItemTemplate in ListView, How to Edit ListView records, How to Update ListView records and How to Cancel ListView update operation. In this article i will explain how to Delete ListView records.

Note: Before reading this article read ASP.Net: ListView Basics - ItemEditing, ItemUpdating and ItemCanceling events.

Add Delete column in LayoutTemplate as shown below:

            <LayoutTemplate>
                <table class="lamp" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                        <th>
                            S.No.
                        </th>
                        <th>
                            Name
                        </th>
                        <th>
                            Email
                        </th>
                        <th>
                            Department
                        </th>
                        <th>
                            Edit
                        </th>
                        <th>
                            Delete
                        </th>
                    </tr>
                    <tr id="itemplaceholder" runat="server">
                    </tr>
                </table>
            </LayoutTemplate>

Add Delete button in ItemTemplate as shown below:

            <ItemTemplate>
                <tr>
                    <td>
                        <%# Container.DataItemIndex + 1%>
                        <asp:HiddenField ID="hfEmployeeID" runat="server" Value='<%#Eval("EmployeeID") %>' />
                    </td>
                    <td>
                        <%#Eval("EmployeeName")%>
                    </td>
                    <td>
                        <%#Eval("Email")%>
                    </td>
                    <td>
                        <%#Eval("DepartmentName")%>
                    </td>
                    <td>
                        <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
                    </td>
                    <td>
                        <asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
                    </td>
                </tr>
            </ItemTemplate>

Add ListView event OnItemDeleting="lvEmployee_ItemDeleting". Now write delete functionality in lvEmployee_ItemDeleting() as shown below:

    protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        try
        {
            // Here 'e.ItemIndex' gets the index of the item being deleted.
            ListViewItem item = lvEmployee.Items[e.ItemIndex];
            HiddenField hfEmployeeID = (HiddenField)item.FindControl("hfEmployeeID");

            string strConnection = @"Data Source = .; Initial Catalog = Test; Integrated Security= true;";
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand cmd = new SqlCommand();
            // delete query.
            cmd.CommandText = @"delete from Employee where EmployeeID = '" + hfEmployeeID.Value + "'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            // Fill Employees
            FillEmployees();
            lblMessage.Text = "Success: Employee Details deleted.";
        }
        catch (Exception ex) { throw ex; }
    }

Run the application. And see the output.

Now click on Delete button respective row will be deleted. If you see we are calling FillEmployees() method after delete operation. Because whatever new data is available the will binded to ListView.

Note: If you click Delete button row will be deleted without user confirmation.

To avoid this we will add user confirmation by using Java Script.

Add OnClientClick event in Delete button as shown below:

<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" OnClientClick="return deleteConfirm();" />

Now add deleteConfirm() function in Java Script as shown below:

    <script type="text/javascript">
        // Confirmation before delete operation.
        function deleteConfirm(sender) {
            var c = confirm("Are you sure?");
            if (c) { return true; } else { return false; }
        }        
    </script>

After adding this run the application. Click Delete button it will ask for user confirmation to delete the row.

Output:

Output(After delete):

Full Source Code:

ListViewEditDemo.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListViewEditDemo.aspx.cs"
    Inherits="ListViewEditDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>List View Edit Example</title>
    <style type="text/css">
        * { font-family: Arial, sans-serif; font-size: 12px; }
        table.lamp { padding: 0px; border: 1px solid #d4d4d4; }
        table.lamp th { color: white; background-color: #666; padding: 10px; padding-left: 10px; text-align: left; }
        table.lamp td { padding: 4px; padding-left: 10px; background-color: #ffffff; }
    </style>
    <script type="text/javascript">
        // Confirmation before delete operation.
        function deleteConfirm(sender) {
            var c = confirm("Are you sure?");
            if (c) { return true; } else { return false; }
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Employee's Data:
    </div>
    <br />
    <div>
        <asp:ListView ID="lvEmployee" runat="server" OnItemEditing="lvEmployee_ItemEditing"
            OnItemUpdating="lvEmployee_ItemUpdating" OnItemCanceling="lvEmployee_ItemCanceling"
            OnItemDeleting="lvEmployee_ItemDeleting">
            <LayoutTemplate>
                <table class="lamp" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                        <th>
                            S.No.
                        </th>
                        <th>
                            Name
                        </th>
                        <th>
                            Email
                        </th>
                        <th>
                            Department
                        </th>
                        <th>
                            Edit
                        </th>
                        <th>
                            Delete
                        </th>
                    </tr>
                    <tr id="itemplaceholder" runat="server">
                    </tr>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <%# Container.DataItemIndex + 1%>
                        <asp:HiddenField ID="hfEmployeeID" runat="server" Value='<%#Eval("EmployeeID") %>' />
                    </td>
                    <td>
                        <%#Eval("EmployeeName")%>
                    </td>
                    <td>
                        <%#Eval("Email")%>
                    </td>
                    <td>
                        <%#Eval("DepartmentName")%>
                    </td>
                    <td>
                        <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
                    </td>
                    <td>
                        <asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" OnClientClick="return deleteConfirm();" />
                    </td>
                </tr>
            </ItemTemplate>
            <EditItemTemplate>
                <tr>
                    <td>
                        <%# Container.DataItemIndex + 1%>
                        <asp:HiddenField ID="hfEmployeeID" runat="server" Value='<%#Eval("EmployeeID") %>' />
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%#Eval("EmployeeName")%>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv_txtEmployeeName" runat="server" ForeColor="Red"
                            Font-Bold="true" Font-Size="18px" ToolTip="Please enter Employee Name." ErrorMessage="*"
                            ControlToValidate="txtEmployeeName" ValidationGroup="vgEmployeeUpdate" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server" Text='<%#Eval("Email")%>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv_txtEmail" runat="server" ForeColor="Red" Font-Bold="true"
                            Font-Size="18px" ToolTip="Please enter Employee Email." ErrorMessage="*" ControlToValidate="txtEmail"
                            ValidationGroup="vgEmployeeUpdate" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:HiddenField ID="hfDepartmentID" runat="server" Value='<%#Eval("DepartmentID") %>' />
                        <asp:DropDownList ID="ddlDepartment" runat="server">
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="rfv_ddlDepartment" runat="server" ForeColor="Red"
                            Font-Bold="true" Font-Size="18px" ToolTip="Please select Department." ErrorMessage="*"
                            ControlToValidate="ddlDepartment" ValidationGroup="vgEmployeeUpdate" Display="Dynamic"
                            InitialValue="-1"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CausesValidation="true"
                            ValidationGroup="vgEmployeeUpdate" />
                    </td>
                    <td>
                        <asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
                    </td>
                </tr>
            </EditItemTemplate>
        </asp:ListView>
    </div>
    <br />
    <div>
        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

ListViewEditDemo.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;

public partial class ListViewEditDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillEmployees();
        }
        lblMessage.Text = "";
    }

    #region FillEmployees()

    /// <summary>
    /// Fill Employees data.
    /// </summary>

    private void FillEmployees()
    {
        try
        {
            string strConnection = @"Data Source = .; Initial Catalog = Test; Integrated Security= true;";
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = @"select E.EmployeeID, E.EmployeeName, E.Email, D.DepartmentID, D.DepartmentName from Employee E inner join Department D on E.DepartmentID = D.DepartmentID";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            lvEmployee.DataSource = ds.Tables[0];
            lvEmployee.DataBind();

            con.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    #endregion

    protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        try
        {
            // This property is set to the index of an item in the control, that item is displayed in edit mode.
            // In edit mode, the item is rendered by using the EditItemTemplate template instead of the ItemTemplate template.
            lvEmployee.EditIndex = e.NewEditIndex;

            // Fill Employee Data.
            FillEmployees();

            // Fill Departments.
            string strConnection = @"Data Source = .; Initial Catalog = Test; Integrated Security= true;";
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = @"select DepartmentID, DepartmentName from Department";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            // Open Connection
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            // Find DropDown Control in InsertItem Template of ListView.
            DropDownList ddl = (DropDownList)lvEmployee.EditItem.FindControl("ddlDepartment");

            ddl.DataSource = ds.Tables[0];
            ddl.DataTextField = "DepartmentName";
            ddl.DataValueField = "DepartmentID";
            ddl.DataBind();

            // Here i'm adding 'Select' Data Text Field to dropdown list.
            ddl.Items.Insert(0, new ListItem(" Select ", "-1"));

            HiddenField hfDepartmentID = (HiddenField)lvEmployee.EditItem.FindControl("hfDepartmentID");
            ddl.SelectedValue = hfDepartmentID.Value;
            // Close Connection
            con.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void lvEmployee_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        try
        {
            // Here 'e.ItemIndex' gets the index of the item being updated.
            ListViewItem item = lvEmployee.Items[e.ItemIndex];
            // Find Employee ID HiddeneField
            HiddenField _hfEmployeeID = (HiddenField)item.FindControl("hfEmployeeID");
            // Find Employee Name TextBox
            TextBox _txtEmployeeName = (TextBox)item.FindControl("txtEmployeeName");
            // Find Email TextBox
            TextBox _txtEmail = (TextBox)item.FindControl("txtEmail");
            // Find Department DropDownList
            DropDownList _ddlDepartment = (DropDownList)item.FindControl("ddlDepartment");

            string strConnection = @"Data Source = .; Initial Catalog = Test; Integrated Security= true;";
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = @"update Employee set EmployeeName = '" + _txtEmployeeName.Text + "', Email = '" + _txtEmail.Text + "', DepartmentID = '" + _ddlDepartment.SelectedValue + "' where EmployeeID = '" + _hfEmployeeID.Value + "'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            // Reset all the fields.
            _txtEmployeeName.Text = "";
            _txtEmail.Text = "";
            _ddlDepartment.SelectedValue = "-1";

            lvEmployee.EditIndex = -1;

            // Bind data to ListView Control.
            FillEmployees();
            lblMessage.Text = "Success: Employee Details Updated.";
        }
        catch (Exception ex) { throw ex; }
    }

    protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        // To switch from edit mode to display mode, set EditIndex property to -1.
        lvEmployee.EditIndex = -1;

        // Fill Employees
        FillEmployees();
    }

    protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        try
        {
            // Here 'e.ItemIndex' gets the index of the item being deleted.
            ListViewItem item = lvEmployee.Items[e.ItemIndex];
            HiddenField hfEmployeeID = (HiddenField)item.FindControl("hfEmployeeID");

            string strConnection = @"Data Source = .; Initial Catalog = Test; Integrated Security= true;";
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand cmd = new SqlCommand();
            // delete query.
            cmd.CommandText = @"delete from Employee where EmployeeID = '" + hfEmployeeID.Value + "'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            // Fill Employees
            FillEmployees();
            lblMessage.Text = "Success: Employee Details deleted.";
        }
        catch (Exception ex) { throw ex; }
    }
}