ASP.Net: ListView Basics - ItemEditing, ItemUpdating and ItemCanceling events

 ASP.Net     sbo     Updated on Sep 01, 2013     VIKRAM     6921   

Introduction:

In this article i will explain how to Edit ListView records, how to Update ListView records and how to Cancel ListView Update operation.

Description:

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

Add new Web form to Website. Name it as ListViewEditDemo.aspxNow drag and drop ListView control from Data controls list and change the ListView ID to lvEmployee.

<asp:ListView ID="lvEmployee" runat="server"> </asp:ListView>

Add LayoutTemplate to ListView control 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 colspan="2">
                            Edit
                        </th>
                    </tr>
                    <tr id="itemplaceholder" runat="server">
                    </tr>
                </table>
            </LayoutTemplate>

Here class="lamp" means it will apply table related style to table. And if you see there is

<tr id="itemplaceholder" runat="server"></tr>

This means Employee related data(all rows) will be rendered here.

Note:

id should be always itemplaceholder and don't forget to add runat="server".

Add 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 colspan="2">
                        <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
                    </td>
                </tr>
            </ItemTemplate>

Here Container.DataItemIndex + 1 means it will give serial number to each row. The default number start from zero. So add 1 to it.

Now bind Employee data to ListView control by using FillEmployee() method.

    #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

Now call FillEmploees() method in Page_Load() event.

Output:

Note:

The ListView control has a built-in editing feature that automatically puts an item in edit mode if you add a button to the item template whose CommandName property is set to Edit.

To fire Edit button event do the following:

1. Set Edit button property CommandName="Edit". 

2. Set ListView event property OnItemEditing="lvEmployee_ItemEditing".

So, when we click on Edit button it will fire OnItemEditing event.

Add EditItemTemplate to ListView control as shown below:

            <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>
Similar to Edit button Add CommandName for Update button and Cancel button. As well as add ListView events onitemupdating="lvEmployee_ItemUpdating" and onitemcanceling="lvEmployee_ItemCanceling" respectively.
Add the following code in lvEmployee_ItemEditing() method.
    protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        try
        {
            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;
        }
    }

Note:

In the above code you will see lvEmployee.EditIndex = e.NewEditIndex;. Here EditIndex property is used to programmatically specify or determine which item in a ListView control to edit. When 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. You can populate the EditItemTemplate with data-bound controls to enable users to modify values for the item. To switch from edit mode to display mode, set this property to -1.

Now click on Edit button you will see the following output.

Output:

Add the following code in lvEmployee_ItemUpdating() method.

    protected void lvEmployee_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        try
        {
            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; }
    }

While updating Employee data it will validate all the fields. Here Validation controls are used to validate the user input.

Output:

In the above output * indicates Department DropDownList value not selected. Select appropriate department for employee and then update the details.

Output:

To perform cancel event add the following code in lvEmployee_ItemCanceling() method.

    protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        lvEmployee.EditIndex = -1;

        // Fill Employees
        FillEmployees();
    }

Note:

To switch from edit mode to display mode, set EditIndex property to -1

Click cancel button to abort update operation.

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>
</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">
            <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 colspan="2">
                            Edit
                        </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 colspan="2">
                        <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
                    </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
        {
            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();
    }
}

 

  Related Articles
The major features added in C# in each release
C# Coding Standards and Naming Conventions
C#: How to Query for characters in a string using LinQ.
C#: How to Read characters from String
ASP.Net: List View Basics - Insert a new record from List View Footer (or) How to use InsertItemTemplate in ListView
ASP.Net: List View Basic Example
Access Specifiers or Access Modifiers in C#
  Recent Articles
The major features added in C# in each release
C# Coding Standards and Naming Conventions
C#: How to Query for characters in a string using LinQ.
C#: How to Read characters from String
ASP.Net: List View Basics - Insert a new record from List View Footer (or) How to use InsertItemTemplate in ListView
ASP.Net: List View Basic Example
Access Specifiers or Access Modifiers in C#