涅槃2012 发表于 2012-10-25 23:58:13

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

在WebForm项目中,列表显示我比较喜欢用Repeater,生成的代码比较干净。不过有一个问题就是当列表为空的时候,为了有较好的用户体验,我们喜欢在界面给出一行提示“查询结果为空”。这时候,.NET自带的Repeater就不能满足需求了,以前通常都是查询出来以后判断一下列表项,一般是datatable或list,如果条数为0,就给出提示,每个列表进行判断,重复代码太多。所以,这里我们想到重写一下Repeater,使其支持一个"空模板",直接代码:

namespace szfsControl
{
    public class Repeater : System.Web.UI.WebControls.Repeater
    {
      private ITemplate emptyDataTemplate;

      typeof(TemplateControl))]
      public ITemplate EmptyDataTemplate
      {
            get { return emptyDataTemplate; }
            set { emptyDataTemplate = value; }
      }
      protected override void OnDataBinding(EventArgs e)
      {
            base.OnDataBinding(e);
            if (emptyDataTemplate != null)
            {
                if (this.Items.Count == 0)
                {
                  EmptyDataTemplate.InstantiateIn(this);
                }
            }
      }
    }
}
页: [1]
查看完整版本: 重写Repeater,使其支持空模版(列表为空时显示)