在ASP.NET 2.0中操作数据之三十五:使用Repeater和DataList单页
目前为止CategoryProductsDataSource ObjectDataSource的categoryID参数还没有设置.所以浏览页面时没有任何的product显示出来.我们现在需要将它设置为Repeater中的被点击的category的CategoryID.这里有两个问题,第一是我们如何判断什么时候Repeater的ItemTemplate被点了.二是哪个被点了. 和Button,ImageButton一样,LinkButton有一个Click event和一个Command event.Click事件仅仅用来说明LinkButton被点击了.有时候我们需要传递更多的信息到event handler里.这样的话,就需要使用LinkButton的CommandName 和CommandArgument .当LinkButton被点时,Command事件激发,event handler会接受CommandName和CommandArgument的值. 当Repeater里的template里激发了一个Command事件时,Rpeater的ItemCommand事件被激发.并将被点击的LinkButton(或者Button和ImageButton)的CommandName和CommandArgument的值传进来.因此,判断category LinkButton什么时候被点击了,我们需要: 设置Rpeater里的ItemTemplate的LinkButton的CommandName属性(我使用的"ListProducts").设置了值后LinkButton被点后Command事件会激发. 设置LinkButton的CommandArgument属性为当前item的CategoryID. 下面是完成了1,2步后的标记.注意CategoryID是如何通过绑定语法来赋给CommandArgument的. <ItemTemplate> <li> <asp:LinkButton CommandName="ListProducts" runat="server" CommandArgument='<%# Eval("CategoryID") %>' ID="ViewCategory" Text='<%# string.Format("{0} ({1:N0})", _ Eval("CategoryName"), Eval("NumberOfProducts")) %>'> </asp:LinkButton> </li> </ItemTemplate> 由于任何一个Button,LinkButton或ImageButton的Command事件都会激发ItemCommand事件,所以无论在任何时候创建ItemCommand event handler首先都要小心谨慎的检查CommandName的值.而由于我们现在只有一个LinkButton,以后我们可能会向Repeater添加新的button控件,当点被点击时,激发同样的ItemCommand event handler.因此最好确保检查了CommandName,然后根据它的值来进行逻辑处理. 在确保了传入的CommandName的值等于"ListProducts"后,event handler将CategoryProductsDataSource ObjectDataSource的CategoryID的参数设为传入的CommandArgument.对ObjectDataSource的SelectParameters的修改自动引起DataList重新绑定到数据源,显示新的选中的category关联的product. protected void Categories_ItemCommand(object source, RepeaterCommandEventArgs e) { // If it's the "ListProducts" command that has been issued... if (string.Compare(e.CommandName, "ListProducts", true) == 0) { // Set the CategoryProductsDataSource ObjectDataSource's CategoryID parameter // to the CategoryID of the category that was just clicked (e.CommandArgument)... CategoryProductsDataSource.SelectParameters["CategoryID"].DefaultValue = e.CommandArgument.ToString(); } } 做完这些后,本章就结束了!现在在浏览器里看看你的页面.图14是第一次浏览时的样子.因为还没有category被选中,所以没有product显示出来.点击一个category,比如Produce,和它关联的product以两列的方式显示出来.见图15.
总结 我们在本章和前面一章里学习了主/从表可以分别显示在两个页或者一起显示在一个页.如果显示在一个页上,我们需要考虑如何来控制它们的外观.在使用GridView 和DetailView实现的主/从报表一章我们将从记录显示在主记录之上,而在本章我们使用CSS将主记录显示在从记录的左边.我们还探讨了如何获取每个category关联的product数量,以及在点击Repeater里的LinkButton(或ButtonImageButton)时服务器端的处理逻辑. 到这里为止使用DataList和Repeater来显示主/从表已经完成了.后面我们将演示如何在DataList里添加编辑和删除的功能. 祝编程愉快! (编辑:淮北站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |