利用ASP.NET程式動態產生DataList的TemplateField欄位,並且繫結資料欄位
最近網友問到這方面的問題...
小弟就實作一個範例,分享給大家呀..
asp.net(c#)範例
DatalistDemo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DatalistDemo.aspx.cs" Inherits="DatalistDemo" %>
<!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>DatalistDemo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" DataKeyField="id">
<ItemTemplate>
id:
<asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>'></asp:Label><br />
gender:
<asp:Label ID="genderLabel" runat="server" Text='<%# Eval("gender") %>'></asp:Label><br />
name:
<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>'></asp:Label><br />
<br />
</ItemTemplate>
</asp:DataList></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
SelectCommand="SELECT * FROM [user]"></asp:SqlDataSource>
</form>
</body>
</html>
<!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>DatalistDemo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" DataKeyField="id">
<ItemTemplate>
id:
<asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>'></asp:Label><br />
gender:
<asp:Label ID="genderLabel" runat="server" Text='<%# Eval("gender") %>'></asp:Label><br />
name:
<asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>'></asp:Label><br />
<br />
</ItemTemplate>
</asp:DataList></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
SelectCommand="SELECT * FROM [user]"></asp:SqlDataSource>
</form>
</body>
</html>
DatalistDemo.aspx.cs























public class DataListTemplate : ITemplate










public void InstantiateIn(System.Web.UI.Control container)





foreach (string item in columnName.Split(','))



Label data = new Label();

data.ID = item;

data.DataBinding += new EventHandler(data_DataBinding);

container.Controls.Add(data);

container.Controls.Add(new LiteralControl("<br/>"));


break;


container.Controls.Add(new LiteralControl("<br/>"));


private void data_DataBinding(object sender, EventArgs e)



DataListItem item = (DataListItem)l.NamingContainer;

l.Text = DataBinder.Eval(item.DataItem,l.ID).ToString();



執行結果:
參考網址:
http://msdn2.microsoft.com/en-us/library/y0h809ak(VS.71).aspx
http://forums.asp.net/p/1087842/1623635.aspx
http://blog.blueshop.com.tw/hent/archive/2008/02/24/54382.aspx