本文描述了如何把Repeater 控件嵌套進DataGrid來顯示分級的數據 。當然,你也可以將這一技術應用到其他的列表綁定控件上去,比如DataGrid包含DataGrid,DataList包含DataList等等的組合。
完整的代碼 如下,要注意的是,
DataGrid1.DataSource=dv;
DataGrid1.DataBind();
一定要在ds.Relations.Add(..)之後..
<%@import namespace="System.Data" %>
<%@import namespace="System.Data.OleDb"%>
<script language="c#" runat="server">
string connstr=ConfigurationSettings.AppSettings["ConnectionString"];
//小區信息
string sql="select * from location where location_id in(select location from catalyst)";
//交換機信息
string sqltext="select * from catalyst order by location desc";
private void page_load(Object obj,EventArgs e)
{
if(!Page.IsPostBack)
{
Dataload();
}
}
private void Dataload()
{
try
{
OleDbConnection conn=new OleDbConnection(connstr);
DataSet ds=new DataSet();
OleDbDataAdapter da=new OleDbDataAdapter(sql,conn);
da.Fill(ds,"location");
DataView dv=new DataView(ds.Tables["location"]);
OleDbDataAdapter da2=new OleDbDataAdapter(sqltext,conn);
da2.Fill(ds,"catalyst");
ds.Relations.Add("myrelation",ds.Tables["location"].Columns["location_id"],ds.Tables["catalyst"].Columns["location"]);
DataGrid1.DataSource=dv;
DataGrid1.DataBind();
conn.Close();
}
catch(OleDbException ex)
{
info.Text=ex.Message;
}
}
</script>
<html>
<body>
<form runat=server>
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn HeaderText="小區名">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"location_name") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="交換機編號">
<ItemTemplate>
<asp:Repeater id="ChildRepeater" DataSource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' runat="server">
<ItemTemplate>
<%# Container.ItemIndex+1%>.<%# DataBinder.Eval(Container.DataItem, "[/"label/"]")%><br>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
<asp:label id="info" forecolor="blue" runat="server"/>
</body>
</html>