ASP.Net: List View Basics - Insert a new record from List View Footer (or) How to use InsertItemTemplate in ListView

 ASP.Net     sbo     Updated on Aug 26, 2013     VIKRAM     3983   

Introduction:

In this article i will explain how to insert a new record from List View's footer (or) How to use InsertItemTemplate in ListView.

Description:

In previous articles i explained How to bind data to List View control. In this article i will explain how to insert a new record from List View's footer (or) How to use InsertItemTemplate in ListView.

Step 1). Drag and Drop List View control

Step 2). Change the List View ID

Step 3). Add Layout Template

Step 4). Add Item Template

Step 5). Create FillEmployees() method to bind Employees data to ListView

Step 6). Call FillEmployees() method in Page_Load() event.

Now the output will be as follows:

We already discussed these steps in our previous article. Now we will see how to add new record by using InsertItemTemplate.

Add InsertItemTemplate to List View.

            <InsertItemTemplate>
                <tr>
                    <td>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmployeeName" runat="server"></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="vgEmployee" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></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="vgEmployee" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <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="vgEmployee" Display="Dynamic"
                            InitialValue="-1"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:Button ID="btnAdd" runat="server" Text=" + Add" CommandName="Insert" CausesValidation="true" ValidationGroup="vgEmployee" />
                    </td>
                </tr>
            </InsertItemTemplate>

In the above source code you will see Emploee Name TextBox, Email TextBox, Department DropDown, and Add Button.

After that add Validation Control's to validate data before adding it to database. Now our requirement is to fill Department dropdown list.

First of all find the Department dropdown list from List View Insert Item Template as below:

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

Now create FillDeprtments() method to fill Departments DropDownList.

    #region FillDepartments()

    /// <summary>
    /// Fill Departments.
    /// </summary>

    private void FillDepartments()
    {
        try
        {
            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;

            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.InsertItem.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"));

            con.Close();
        }
        catch (Exception ex) { throw ex; }
    }

    #endregion

 

Now call both the methods FillEmployees() and FillDepartments() in Page_Load() event.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillEmployees();
            FillDepartments();
        }
        lblMessage.Text = "";
    }

Now set ListView's InsertItemPosition property to LastItem. So, that the InsertItemTemplate will be displayed at the end of ListView.

Output:

Now set Add button's CommandName prporty to Insert. So that it will call lvEmployee_ItemInserting event.

Add OnItemInserting="lvEmployee_ItemInserting".

    protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        try
        {
        }
        catch (Exception ex) { throw ex; }
    }

When add button is clicked then lvEmployee_ItemInserting event will be fired. Here we will write new record insert related functionality.

    protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        try
        {
            // Find Employee Name TextBox
            TextBox _txtEmployeeName = (TextBox)e.Item.FindControl("txtEmployeeName");
            // Find Email TextBox
            TextBox _txtEmail = (TextBox)e.Item.FindControl("txtEmail");
            // Find Department DropDownList
            DropDownList _ddlDepartment = (DropDownList)e.Item.FindControl("ddlDepartment");

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

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = @"insert into Employee(EmployeeName, Email, DepartmentID) values('" + _txtEmployeeName.Text + "','" + _txtEmail.Text + "','" + _ddlDepartment.SelectedValue + "')";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

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

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

            // Bind data to ListView Control.
            FillEmployees();
            // Bind Departments.
            FillDepartments();

            lblMessage.Text = "Success: Details Inserted.";
        }
        catch (Exception ex) { throw ex; }
    }

Insert New Record:

Display Emploee Data:

Full Source Code:

ListViewInsertDemo.aspx:

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

<!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 Insert 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" InsertItemPosition="LastItem" OnItemInserting="lvEmployee_ItemInserting">
            <LayoutTemplate>
                <table class="lamp" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                        <th>
                            S.No.
                        </th>
                        <th>
                            Name
                        </th>
                        <th>
                            Email
                        </th>
                        <th colspan="2">
                            Department
                        </th>
                    </tr>
                    <tr id="itemplaceholder" runat="server">
                    </tr>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <%# Container.DataItemIndex + 1%>
                    </td>
                    <td>
                        <%#Eval("EmployeeName")%>
                    </td>
                    <td>
                        <%#Eval("Email")%>
                    </td>
                    <td>
                        <%#Eval("DepartmentName")%>
                    </td>
                    <td>
                    </td>
                </tr>
            </ItemTemplate>
            <InsertItemTemplate>
                <tr>
                    <td>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmployeeName" runat="server"></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="vgEmployee" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></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="vgEmployee" Display="Dynamic"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <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="vgEmployee" Display="Dynamic"
                            InitialValue="-1"></asp:RequiredFieldValidator>
                    </td>
                    <td>
                        <asp:Button ID="btnAdd" runat="server" Text=" + Add" CommandName="Insert" CausesValidation="true" ValidationGroup="vgEmployee" />
                    </td>
                </tr>
            </InsertItemTemplate>
        </asp:ListView>
    </div>
    <br />
    <div>
        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

ListViewInsertDemo.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 ListViewInsertDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillEmployees();
            FillDepartments();
        }
        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

    #region FillDepartments()

    /// <summary>
    /// Fill Departments.
    /// </summary>

    private void FillDepartments()
    {
        try
        {
            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;

            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.InsertItem.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"));

            con.Close();
        }
        catch (Exception ex) { throw ex; }
    }

    #endregion

    protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        try
        {
            // Find Employee Name TextBox
            TextBox _txtEmployeeName = (TextBox)e.Item.FindControl("txtEmployeeName");
            // Find Email TextBox
            TextBox _txtEmail = (TextBox)e.Item.FindControl("txtEmail");
            // Find Department DropDownList
            DropDownList _ddlDepartment = (DropDownList)e.Item.FindControl("ddlDepartment");

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

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = @"insert into Employee(EmployeeName, Email, DepartmentID) values('" + _txtEmployeeName.Text + "','" + _txtEmail.Text + "','" + _ddlDepartment.SelectedValue + "')";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

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

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

            // Bind data to ListView Control.
            FillEmployees();
            // Bind Departments.
            FillDepartments();

            lblMessage.Text = "Success: Details Inserted.";
        }
        catch (Exception ex) { throw ex; }
    }
}
  Related Articles
ASP.Net: ListView Basics - ItemEditing, ItemUpdating and ItemCanceling events
ASP.Net: List View Basic Example
  Recent Articles
ASP.Net: ListView Basics - ItemEditing, ItemUpdating and ItemCanceling events
ASP.Net: List View Basic Example