天涯之外

导航

Repeater简单应用(动态改变内部样式)

闲话少说,还是说说今天要谈的:Reteater,做asp.net的朋友可能都很喜欢的好东西,先插句,不是说GridView,DataList这类不好,看在什么地方什么情况下应用了,不过在前台页面显示来说,还是比较喜欢Repeater,性能好,而且很灵活,今天就举个我在刚进公司时遇到的关于Repeater在小问题。
    先说下问题,在一个UL,LI显示图片列表中,要求每行显示四个图片,本以为是一个超简单的,也很有自信,拿过Repeater就编辑模板,可是我没有注意到,每行的LI应用的样式不同,所以问题也来了,经过一翻“折腾”,终于找着了解决办法。
   先看下写完的模板:
Code
               
<asp:Repeater ID="Repeater1" runat="server" OnItemCreated="Repeater1_ItemCreated">
                    
<HeaderTemplate>
                        
<ul class="healweek">
                    
</HeaderTemplate>
                    
<ItemTemplate>
                        
<li id="rep" runat="server"><a href="health_idea_detail.aspx?id=<%#Eval("id") %>&type=3">
                           
<asp:Image ID="Image3" runat="server" ImageUrl='<%#Eval("Defaultimage","~/img/small/health/{0}") %>'
                                AlternateText
='<%#Eval("idearname") %>' Width="160" Height="120"
/></a>
<span><a
                                    href
="health_idea_detail.aspx?id=<%#Eval("id") %>&type=3">
                                    
<%#Eval("idearname") %></a></span></li>
                    
</ItemTemplate>
                    
<FooterTemplate>
                        
</ul>
                    
</FooterTemplate>
               
</asp:Repeater>

(为了完整性,把UL也添加在了头部)
除了普通的方式编写模板及内部的绑定数据外,在ItemTemplate内在li改为了<li id="rep" runset="server">
关键就在这,这样就可以在CS文件里对LI进行动态操作,其他的都是再普通不过的绑定数据了。

Repeater1_ItemCreated事件中对它进行了操作,如下:
Code
protected
void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
   
{
        
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        
{
            
if ((e.Item.ItemIndex +
1) %
4
==
0)
            
{
                HtmlControl divContent
= e.Item.FindControl("rep") as HtmlControl;
                divContent.Attributes.Add(
"class", "lastChild");
            }

        }

    }


解释下:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
大家非常熟悉,判断模板内容项的
if ((e.Item.ItemIndex + 1) % 4 == 0)
这个就是进行判断哪一项是要进行更改样式,上例中是对每行最后一项也就是第4,8..进行更新样式,所以在这里当ItemIndex=3,7..时就执行下面的操作:
HtmlControl divContent = e.Item.FindControl("rep") as HtmlControl;
                divContent.Attributes.Add("class", "lastChild");

查找出REP,对其样式修改为lastChild就OK了!
这只是一个非常简单的应用,多了解控件的运行周期感觉挺有用。
当然也有别的方法可以实现,也可以在HTML页面进行<%%>来动态输出(asp.net mvc中常用)。

posted on 2009-03-08 20:05  天涯之外  阅读(484)  评论(0编辑  收藏  举报