获取Repeater控件中的控件要注意的小问题

Posted on 2008-04-14 09:45  名号M  阅读(2091)  评论(0)    收藏  举报
     为了得到repeater控件中的控件,之前查了一些文章,大概就是使用RepeaterItem.FindControl()方法来从Repeater.Controls中获取。但我一开始是把代码加到PageLoad中,导致出不来效果。后来注意到在PageLoad的时候,Repeater还没有进行绑定,所以也就无从取得其中绑定的控件了。我们可以在ItemCreated或者ItemDataBound事件中获取模板列中的控件,那时Repeater中已经有控件了。比如下面的代码:
protected void RpSection_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            foreach (RepeaterItem item in RpSection.Controls)
            {
                if (item.FindControl("LblSection") is Label)
                {
                    if (((Label)item.FindControl("LblSection")).Text == loginUser.Section)
                    {
                        ((Label)item.FindControl("LblSection")).BackColor = System.Drawing.Color.Blue;
                    }
                }
            }
        }
    在这之前,我在if (item.FindControl("LblSection") is Label)语句之前还判断了一下:    if(item.ItemType == ListItemType.Item)
    这样的结构导致,偶数项还是获取不到。后来调试了下才发现,偶数项的ItemType是AlternatingItem类型的,这也是要注意的啦。

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3