<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataList控件.aspx.cs" Inherits="WebApplication1.DataList控件" %> <!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>DataList嵌套绑定例子</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DataList ID="DataList1" runat="server" RepeatColumns="2" RepeatDirection="Horizontal" OnItemDataBound="DataList1_ItemDataBound"> <ItemTemplate> <div style="background-color:Green"> <asp:Label ID="Label1" runat="server" Text='<%#Eval("Sex")%>' Visible="false"></asp:Label> <%#bool.Parse(Eval("Sex").ToString())==true?"男":"女" %> </div> <asp:DataList ID="DataList2" runat="server"> <ItemTemplate> <%#Eval("RealName")%> </ItemTemplate> </asp:DataList> </ItemTemplate> </asp:DataList> </div> </form> </body> </html>
CS代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace WebApplication1 { public partial class DataList控件 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindSex(); } } //绑定顶级项目 private void BindSex() { SqlConnection conn = new SqlConnection(@"server=Rose-PCSQLEXPRESS;Database=User;User Id=sa;password="); SqlCommand command = new SqlCommand("Select distinct Sex from UserInfo", conn); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable data = new DataTable(); adapter.Fill(data); DataList1.DataSource = data; DataList1.DataBind(); } //当绑定DataList1中的每一项时的处理方法 protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) { //如果要绑定的项是交替项或者是普通项 if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { //e.Item表示当前绑定的那行 //利用e.Item.FindControl("Label1")来找到那一行的id为“Label”的Label控件 Label lbSex = (Label)(e.Item.FindControl("Label1")); //利用e.Item.FindControl("DataList2")来找到那一行的id为“DataList2”的DataList2控件 DataList dl2 = (DataList)(e.Item.FindControl("DataList2")); bool male = bool.Parse(lbSex.Text); dl2.DataSource = GetDataTable(male); dl2.DataBind(); } } private DataTable GetDataTable(bool male) { SqlConnection conn = new SqlConnection(@"server=Rose-PCSQLEXPRESS;Database=User;User Id=sa;password="); SqlCommand command = new SqlCommand("Select top 3 RealName from UserInfo where Sex=@Sex order by ID", conn); command.Parameters.AddWithValue("@Sex", male); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable data = new DataTable(); adapter.Fill(data); return data; } } }
注意:上面的代码使用了两个DataList控件,第二个位于itemTemplate模板里,用于绑定当前数据,在第一个itemTemplate里还用到一个Label控件,这个是不可见的(visible=“false”) 这个不是为了显示数据,是为了保护第二个DataList控件要绑定显示数据的条件