aspx页面代码
内嵌的DataList在页面使用后台的GetDetails方法绑定
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataListNesting.aspx.cs" Inherits="DataListNesting" %>
<!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 id="Head1" runat="server">
<title>DataListNesting</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("OrderID") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
</div>
<asp:DataList ID="DataList2" runat="server" DataSource='<%# GetDetails(Eval("OrderID").ToString()) %>'>
<ItemTemplate>
<div>
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval( (Container.NamingContainer.NamingContainer as DataListItem).DataItem, "CustomerID" ) %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("UnitPrice") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Quantity") %>'></asp:Label>
</div>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
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.Data.SqlClient;
public partial class DataListNesting : System.Web.UI.Page
{
private void BindList()
{
SqlConnection cn = new SqlConnection(@"server=./sqlexpress;uid=sa;pwd=;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("select OrderID, CustomerID from Orders", cn);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
cn.Close();
DataList1.DataSource = ds.Tables[0].DefaultView;
DataList1.DataKeyField = "orderID";
DataList1.DataBind();
}
protected DataTable GetDetails(string orderID)
{
SqlConnection cn = new SqlConnection(@"server=./sqlexpress;uid=sa;pwd=;database=northwind;");
SqlDataAdapter da = new SqlDataAdapter("select ProductID, UnitPrice, Quantity from [Order Details] where orderID = @orderID", cn);
da.SelectCommand.Parameters.AddWithValue("@orderID", orderID);
DataSet ds = new DataSet();
cn.Open();
da.Fill(ds);
cn.Close();
return ds.Tables[0];
}
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
BindList();
}
}
}
其中DataList2中的Label1得到的是父容器数据项中的值