A DataBinding expression is a special type of expression not evaluated until
runtime. We
mark a databinding expression in a page by wrapping the expression in opening
<%# and closing %>
brackets.
A DataBinding expression isn’t evaluated until a control’s DataBinding event
is raised.
When we bind a DataBound control to a DataSource control declaratively, this event
is
raised automatically. When we bind a DataSource control to a data source programmatically,
the DataBinding event is raised when we call the DataBind() method.
The first DataBinding expression displays the Name of the Employee and the
second
DataBinding expression displays the Hire date of Employee.
Both DataBinding expressions call the Eval() method. The Eval() method is
a protected
method of the Page class. Behind the scenes, the Page.Eval() method calls the static
(shared) DataBinder.Eval() method. If we want to be verbose, instead of using the
Eval() method, we could use the following two expressions:
<%# DataBinder.Eval(Container.DataItem, "Name") %>
<%# DataBinder.Eval(Container.DataItem, "hire_date", "{0:D}" ) %>
The second DataBinding expression includes a second parameter. The
Eval() method, optionally, accepts a format string. We can use the
String Format
to
format values such as dates and currency amounts.
We can call other methods than the Eval() method in a DataBinding expression.
For
example, the DataBinding expression a method named FormatName()
to format the Employee names.
Code: ShowDataList.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowDataList.aspx.cs"
Inherits="LearnAsp.Net.ControlDemo.DataBound.ShowDataList" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" DataSourceID="srcEmployees" RepeatColumns="4" runat="server"
RepeatDirection="Horizontal" BackColor="Aquamarine" Caption="Employees Details">
<ItemTemplate>
<b>Employee Name:</b>
<%# FormatName( Eval("Name")) %>
<br />
<b>Hire Date:</b>
<%#Eval("hire_date", "{0:D}")%>
<br />
<b>Salary:</b>
<%#Eval("salary")%>
<hr />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="srcEmployees" ConnectionString="<%$ ConnectionStrings:constrOracle %>"
ProviderName="System.Data.OracleClient"
SelectCommand=" select first_name||' '||last_name as Name,hire_date,salary from employees "
runat="server" />
</div>
</form>
</body>
</html>
Code: ShowDataList.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LearnAsp.Net.ControlDemo.DataBound
{
public partial class ShowDataList : System.Web.UI.Page
{
public string FormatName(Object Name)
{
return "" + Name.ToString().ToUpper() + "";
}
}
}
No comments:
Post a Comment
Please do not enter any spam link in the comment box.