重写Repeater,使其支持空模版(列表为空时显示) 。改进

最近项目需要,在网上搜索Repeater为空时提示解决方法。有两种方法,一种是在FooterTemplate模板中放一个隐藏控件,用Repeater.Items.Count ==0 判断是否显示。比如这篇文章就是用的这种方法。
第二种方法相对复杂一点,用的是重写Repeater。具体方法见这篇文章
 
不过这两篇文章的方法都有点小问题,显示在FooterTemplate模板中间或之后,有什么缺点这就不说了,这里说下解决方法。
直接上代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.UI;
namespace MyRepeater
{
    public class Repeater : System.Web.UI.WebControls.Repeater
    {
        [PersistenceMode(PersistenceMode.InnerProperty), Browsable(false), TemplateContainer(typeof(TemplateControl))]
        public ITemplate EmptyDataTemplate{get;set;}
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            if (EmptyDataTemplate != null)
            {
                if (this.Items.Count == 0)
                {
                    EmptyDataTemplate.InstantiateIn(this);
                }
            }
        }
        protected override void RenderChildren(HtmlTextWriter output)
        {
            if (HasControls())
            {
                for (int i = 0; i < Controls.Count; i++)
                {
                    if (this.FooterTemplate != null && this.Items.Count == 0 && EmptyDataTemplate != null)
                    {
                        if (i == Controls.Count - 2)
                        {
                            Controls[i + 1].RenderControl(output);
                            continue;
                        }
                        if (i == Controls.Count - 1)
                        {
                            Controls[i - 1].RenderControl(output);
                            continue;
                        }
                    }
                    Controls[i].RenderControl(output);
                }
            }
        }
        protected override void Render(HtmlTextWriter output)
        {
            RenderChildren(output);
        }
    }
}


效果测试

前台代码

 

后台代码

 

显示效果

 

生成代码

 

源码地址,包括测试代码

http://my-repeater.googlecode.com/svn



posted @ 2012-11-22 12:57  Adming  阅读(271)  评论(0编辑  收藏  举报