前台页面代码:
1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataContainer.aspx.cs" Inherits="test_DataBind_DataContainer" %>
2<%@ Import Namespace="System.Data" %>
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7 <title>无标题页</title>
8</head>
9<body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:DataList ID="DataList1" runat="server">
13 <ItemTemplate>
14 数字:<%# ((DataRowView)Container.DataItem)["num"] %>
15 平方:<%# (int)((DataRowView)Container.DataItem)["num"] * (int)((DataRowView)Container.DataItem)["num"] %>
16 货币:<%# DataBinder.Eval(Container.DataItem,"num","{0:p}") %>
17 </ItemTemplate>
18 </asp:DataList></div>
19 </form>
20</body>
21</html>
22
后台页面代码:
1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12public partial class test_DataBind_DataContainer : System.Web.UI.Page
13{
14 protected void Page_Load(object sender, EventArgs e)
15 {
16 if(!this.IsPostBack)
17 {
18 DataTable dt = new DataTable(); //先定义一个数据表对象.
19 dt.Columns.Add("num",typeof(int));//添加列 参数:字段名称,数据类型
20 for (int i = 0; i < 10;i++ )
21 {
22 DataRow dr = dt.NewRow(); //添加行,注意写法: dt.NewRow();
23 dr[0] = i;
24 dt.Rows.Add(dr); //将行添加到项目中.
25 }
26 this.DataList1.DataSource = dt;
27 this.DataList1.DataBind();
28 }
29 }
30}
31