【转自 http://www.cnblogs.com/caodaiming/archive/2008/12/18/1357660.html】
今天在网上看到一段代码,是关于Repeater 嵌套的问题,有很多的不明白的地方,希望大家能帮我把这个迷解了;
先看运行的效果:

XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book type="计算机">
<context>C语言</context>
<context>C#语言</context>
<context>C++语言</context>
</book>
<book type="小说">
<context>爱情小说</context>
<context>知音小说</context>
<context>军事动态</context>
</book>
</books>
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Test.xml"));
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater p = (Repeater)e.Item.FindControl("Repeater2");
DataRowView drv = (DataRowView)e.Item.DataItem;
p.DataSource = drv.CreateChildView("book_context");
p.DataBind();
}
}
前台代码:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
Repeater Test</HeaderTemplate>
<FooterTemplate>
</FooterTemplate>
<ItemTemplate>
<ul>
<%#Eval("type") %>
<br />
</ul>
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<%#Eval("context_Text")%><br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
不明的地方是:
1、 p.DataSource = drv.CreateChildView("book_context"); 中的“book_context”为什么是这样的参数,修改成其它的参数报错:
去MSDN中查CreateChildView方法解释如下:
如果 DataSet 中的表之间存在关系,则可以使用 DataRowView 的 CreateChildView 方法为父表中的行创建一个 DataView,包含相关子表中的行;具体也没有说明什么,它只是说父表与子表的关系;
2、前面页面代码
<ItemTemplate>
<%#Eval("context_Text")%><br />
</ItemTemplate>
梆定XML中的context的时候只能是context_Text字段;修改成context是报错;但是按照我们一般性的理解,应该是梆定XML中的字段啊!
本文探讨了ASP.NET中Repeater控件的嵌套使用方法,并通过实例解析了如何从XML文件读取数据并正确绑定到Repeater控件上。重点介绍了CreateChildView方法的使用及常见错误。
3233

被折叠的 条评论
为什么被折叠?



