ASP.NET

ItemDataBound Event in DataList

Programmingempire

Basically, the ItemDataBound Event in DataList is one of the several events that occur when an item is data-bound to the DataList control. The following article shows an application of the ItemDataBound event.

Before proceeding further, you can get a basic understanding of the DataList control by going through the following topics.

Example of ItemDataBound Event in DataList

As can be seen in the following ASPX file, it contains a DataList control. Further, the DataList control creates two templates – the ItemTemplate, and the FooterTemplate. Evidently, it also handles the ItemDataBound event.

Since, both ItemTemplate and the FooterTemplate contain Label control to display the data values, they use the data binding expressions in their Text property. Basically, the Eval(Object, String) method dynamically evaluates a data binding expression. Furthermore, the FooterTemplate also contains a Label control having a data binding expression to display the computed value.

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DataListDemo2.WebForm1" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
             <asp:DataList ID="DataList1" runat="server" BackColor="LightCyan" 
        ForeColor="Navy" CellPadding="1" Width="100%"
    CellSpacing="3" DataKeyField="A" BorderColor="DarkMagenta" BorderWidth="6" 
        BorderStyle="Solid" ShowFooter="true" 
         onitemdatabound="DataList1_ItemDataBound">
    <HeaderStyle BackColor="DarkBlue" ForeColor="LightCyan" Font-Bold="true" Font-Size="XX-Large"
    HorizontalAlign="Left" BorderColor="DarkMagenta" BorderWidth="3" BorderStyle="Solid"/>
    <HeaderTemplate>Item Details<br />
   <asp:Literal id="Literal1" runat="server"><h5><pre>Item ID      Item Name        Price         Quantity</pre></h5></asp:Literal>
    </HeaderTemplate>
    <ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%#Eval("A") %>' Width="200"></asp:Label>
    <asp:Label ID="Label2" runat="server" Text='<%#Eval("B") %>' Width="200"></asp:Label>
    <asp:Label ID="Label3" runat="server" Text='<%#Eval("C") %>' Width="200"></asp:Label>
    <asp:Label ID="Label4" runat="server" Text='<%#Eval("D") %>' Width="200"></asp:Label>
    </ItemTemplate>

  <SeparatorStyle BackColor="DarkGoldenrod" height="1%" />
  <SeparatorTemplate></SeparatorTemplate>
    <FooterStyle BackColor="Navy" ForeColor="MintCream" HorizontalAlign="Center" Font-Bold="true" 
    Font-Size="Large" BorderColor="DarkMagenta" BorderStyle="Solid" BorderWidth="3"/>
    <FooterTemplate>Total Cost: 
    <asp:Label ID="Label5" runat="server" Text='<%#Eval("E") %>'></asp:Label>
    </FooterTemplate>
    </asp:DataList>
  </div>
 </form>
</body>
</html>

The following code shows how the DataList control displays data in its templates. Basically, the data is retrieved from a SQL Server database that has a table called Items containing four fields – item_id, item_name, price, and quantity.

Further, we create a DataSet object and fetch the data from this table using the specified query. After that, the DataSet object is loaded with the query result using the Fill() method. Afterward, a DataView object is created with this data that acts as the data source for the DataList.

It is important to realize that while we create the DataTable object by adding data rows in the foreach loop, we compute the variable total also. Further, the same variable has been used in the ItemDataBound event handler

Meanwhile, the ItemDataBound event handler first verifies that the data item will be bound to a control in the FooterTemplate. After that, we use the FindControl() method to search for the specific Label control and then bind the variable total to it.

WebForm1.aspx.cs

using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace DataListDemo2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        int q;
        SqlConnection con;
        SqlDataAdapter da;
        DataSet ds;
        double total = 0;
        ICollection GetData()
        {
            con = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=C:UsersKAVITADocumentsd1.mdf;Integrated Security=True;Connect Timeout=30");
            da = new SqlDataAdapter("select * from Items", con);
            con.Open();
            ds = new DataSet();
            da.Fill(ds, "MyItems");

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("A", typeof(Int32)));
            dt.Columns.Add(new DataColumn("B", typeof(String)));
            dt.Columns.Add(new DataColumn("C", typeof(Int32)));
            dt.Columns.Add(new DataColumn("D", typeof(Int32)));
            DataRow dr;

            foreach (DataRow r1 in ds.Tables["MyItems"].Rows)
            {
                dr = dt.NewRow();
                dr[0] = r1[0];
                dr[1] = r1[1];
                dr[2] = r1[2];
                dr[3] = r1[3];
                double x = Double.Parse(dr[2].ToString());
                int y = Int32.Parse(dr[3].ToString());
                total += x * y;
                dt.Rows.Add(dr);
            }
            DataView dv = new DataView(dt);
            return dv;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindList();
        }
        public void BindList()
        {
            DataList1.DataSource = GetData();
            DataList1.DataBind();
            con.Close();
        }
        protected void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label LT1 = (Label)e.Item.FindControl("Label5");
                LT1.Text = total.ToString("C3");
            }
        }
    }
}

Output

Example of ItemDataBound Event in DataList
Example of ItemDataBound Event in DataList

Further Reading

Parameter and ParameterCollection in ADO.NET

Database Manipulation Using DataGrid

Example of Button and Link Button Control in ASP.NET

Example of Chart Control in ASP.NET

Creating a DataTable from a DataReader in ASP.NET

Deleting a Record using DataGrid Control in ASP.NET

Edit a Record Using DataGrid Control in ASP.NET

Insert a Record Using ItemCommand Event in DataGrid

CRUD Operations with DataGrid in ASP.NET

Creating Columns in a DataGrid Control

XML Documents and DataSet in ASP.NET

Code Render Block in ASP.NET

ASP.NET Core Features and Advantages

Display Images Using DataList Control

Adding Images Using Image Control

Creating a Group of Radio Buttons Using RadioButtonList Control

Example of Button Control in ASP.NET

Using MD5 Hash Algorithm

ItemDataBound Event in DataList

More Features of DataList in ASP.NET

A Simple Example of Using a DataList Control in ASP.NET

Properties and Methods of DataList Control in ASP.NET

ASP.NET Practice Exercise

Exploring DataList Control in ASP.NET

Custom Validator Control in ASP.NET

Validation Summary Control in ASP.NET

Validation Controls Examples – RequiredFieldValidator, CompareValidator, and RangeValidator

An Example of Data Binding with RadioButtonList Control

Binding Data to Web Control in ADO.NET

Examples of AdRotator Control in ASP.NET

Examples of Validation Controls in ASP.NET

Overview of MVC architecture in ASP.NET

programmingempire

You may also like...