本文主要是介绍.NET中DataList嵌套说明,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
.NET中DataList嵌套说明
有时在我们进行数据绑定时,是可能需要进行嵌套绑定的,以显示主从关系的数据。即,一个DataList中嵌套一个子DataList,而子DataList的数据则是随主DataList的数据进行变化的。
1、我们先在页面中布置好两个DataList。并分别起名,dlsProductMenu,dlsProductInfo。如下:
<TABLE id="Table3" cellSpacing="0" cellPadding="0" width="90%" align="center" border="0">
<TBODY>
<TR>
<TD vAlign="top">
<!--主菜单开始--><asp:datalist id="dlsProductMenu" runat="server" RepeatDirection="Horizontal" RepeatColumns="2"
Width="100%">
<ItemTemplate>
<TABLE class="table02" id="Table13" cellSpacing="0" cellPadding="0" width="100%" align="center"
border="0">
<TR bgColor="#f5f5f5">
<TD width="50%" height="30">
<%# DataBinder.Eval(Container.DataItem,"Name") %>
</TD>
</TR>
</TABLE>
<!--子菜单开始-->
<asp:datalist id="dlsProductInfo" Width="100%" runat="server" RepeatColumns="1">
<ItemTemplate>
<TABLE class="table02" id="Table14" cellSpacing="0" cellPadding="0" width="100%" align="center"
border="0">
<TR bgColor="#f5f5f5">
<TD width="50%" height="30">
<DIV class="style10" align="left">标题: <a href='ProductInfoDetail.aspx?subID=<%# DataBinder.Eval(Container.DataItem,"subID") %>'>
<%# DataBinder.Eval(Container.DataItem,"Title") %>
</a>
</DIV>
</TD>
</TR>
</TABLE>
</ItemTemplate>
</asp:datalist>
<!--子菜单结束-->
</ItemTemplate>
</asp:datalist>
<!--主菜单结束--></TD>
</TR>
</TBODY>
</TABLE>
2、进行数据绑定。
(1)为主DataList绑定主数据。
DataSet ds = SqlDataProvider.GetMainInfo();//获取将要绑定的数据。
this.dlsProductMenu.DataSource = ds;
this.dlsProductMenu.DataBind();
(2)为子DataList绑定从数据。这也是该文的重点。
DataList嵌套的重点是要在外层DataList的ItemDataBound事件中完成对嵌套DataList的绑定。在主DataList的ItemDataBound事件中用e.Item.FindControl方法来找到嵌套层DataList的id,完后为该id绑定数据。比如:
private void dlsProductMenu_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item||e.Item.ItemType == ListItemType.AlternatingItem)
{
DataList dataList = (DataList)e.Item.FindControl("dlsProductInfo");
DataRowView rowv = (DataRowView)e.Item.DataItem;
int mainID = Convert.ToInt32(rowv["Id"]);
if(mainID > 0)
{
DataSet ds = SqlDataProvider.GetSubContent(mainID);//获取从数据。
if(ds != null)
{
try
{
dataList.DataSource = ds;
dataList.DataBind();
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
}
这篇关于.NET中DataList嵌套说明的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!