先建一个Student类:
/// <summary>
/// 学生类
/// </summary>
public class Student
{
private String _Name;
private Int32 _Age;
public Student(String name, Int32 age)
{
//
// TODO: 在此处添加构造函数逻辑
//
_Name = name;
_Age = age;
}
/// <summary>
/// 姓名
/// </summary>
public String Name
{
get { return _Name; }
set { _Name = value; }
}
/// <summary>
/// 年龄
/// </summary>
public Int32 Age
{
get { return _Age; }
set { _Age = value; }
}
}List数据集绑定至DataList:
Test.aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!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数据源绑定至DataList示例</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("name") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("age") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>Test.aspx.cs代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Student> classa = new List<Student>();
Student aa = new Student("AA", 20);
Student bb = new Student("BB", 21);
Student cc = new Student("CC", 22);
Student dd = new Student("DD", 23);
classa.Add(aa);
classa.Add(bb);
classa.Add(cc);
classa.Add(dd);
DataList1.DataSource = classa;
DataList1.DataBind();
}
}绑定过程都差不多,主要就是在模板中怎么显示对象的属性,可以看到,和显示DataTable字段的值是一样的。
评论(0)
暂无评论。