• WebForm(四)——Repeater控件(重要、好用)


           Repeater控件,可以用来一次显示一组数据项。比如,可以用它们显示一个数据表中的所有行。     
           Repeater控件完全由模板驱动,提供了最大的灵活性,可以任意设置它的输出格式

    一、Repeater控件显示数据

          要使用Repeater控件显示数据,必须创建ItemTemplate。如下所示:

         
    例1:使用ItemTemplate显示数据  

    <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
        <ItemTemplate>
            <div class="movies">
                <h1><%#Eval("Title") %></h1>
            </div>
            <b>Directed by:</b><%#Eval("Director") %>
            <br />
            <b>Description:</b><%#Eval("Description") %>
        </ItemTemplate>
    </asp:Repeater> 
    View Code

          以上代码,通过浏览器可以看到,.net不会改变里面的结构,模板里面怎么排列,数据显示也怎么样显示。它的HTML如下所示:

    <div class="movies">
         <h1>史密斯行动</h1>
    </div>
    <b>Directed by:</b>Doug Liman
    <br />
    <b>Description:</b>约翰(布拉德?皮特 Brad Pitt 饰)和
    <div class="movies">
         <h1>暴力街区</h1>
    </div>
    <b>Directed by:</b>Luc Besson
    <br />
    <b>Description:</b>卧虎藏龙而又凌乱不堪的13区… 
    View Code

          所以,Repeater的灵活性就在这个上面,完全可以自由发挥,想怎么显示就怎么显示。例如,都可以把它放在Javascript代码中     

    <script type=”text/javascript”>
        <asp:Repeater id=”rptPhotos” Runat=”server”>
             <ItemTemplate>
                  <%# Eval(“Name”, "photos.push(‘Photos/{0}’)") %>
             </ItemTemplate>
        </asp:Repeater>
    </script> 
    View Code

          以上,photos是一个Javscript数组对象。Repeater生成的数据,最后就像以下这样:   

    <script type="text/javascript">
            photos.push('Photos/1.jpg');
            photos.push('Photos/2.jpg');
            photos.push('Photos/3.jpg');
            photos.push('Photos/4.jpg');
            …
    </script> 
    View Code

    二、Repeater中使用模板
          Repeater支持以下5种模板      
                 ● ItemTemplate : 对每一个数据项进行格式设置 【Formats each item from the data source.】      
                 ● AlternatingItemTemplate : 对交替数据项进行格式设置     
                 ● SeparatorTemplate : 对分隔符进行格式设置     
                 ● HeaderTemplate : 对页眉进行格式设置 ,在加载开始执行一遍   
                 ● FooterTemplate : 对页脚进行格式设置,在加载最后执行一遍     
           以上,英文中使用了Formats item from datasource这样的话,就说明Repeater控件主要是用来对数据进行Format的,控制数据怎么样排列,怎么样显示。     
           Repeater必须使用的是Itemtemplate,其它的类型模板按需添加。     
    例2:以下通过CSS控制,显示了一个比较不错的列表项,要求:①性别由布尔型转成字符串显示:true—男;false—女

                                                                                      ②民族将民族代号转成名族名称显示

                                                                                      ③生日显示:yyyy年MM月dd日的形式(对于要求建议用扩展属性的方法)

    数据库连接类: 

    /// <summary>
    /// Nation 的摘要说明
    /// </summary>
    public class Nation
    {
        
        private string _NationCode;
    
        public string NationCode
        {
            get { return _NationCode; }
            set { _NationCode = value; }
        }
        private string _NationName;
    
        public string NationName
        {
            get { return _NationName; }
            set { _NationName = value; }
        }
    }
    Nation
    /// <summary>
    /// NationDA 的摘要说明
    /// </summary>
    public class NationDA
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        public NationDA()
        {
            conn = new SqlConnection("server=.;database=Data0617;user=sa;pwd=128712jdhlys");
            cmd = conn.CreateCommand();
        }
    
        public Nation Select(string Ncode)
        {
            Nation n = new Nation();
    
            cmd.CommandText = "select *from Nation where NationCode = @a";
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@a", Ncode);
    
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                dr.Read();
                n.NationCode = dr["NationCode"].ToString();
                n.NationName = dr["NationName"].ToString();
            }
            conn.Close();
            return n;
        }
    }
    NationDA
    /// <summary>
    /// Users 的摘要说明
    /// </summary>
    public class Users
    {
        
        private string _UserName;
        /// <summary>
        /// 账号
        /// </summary>
        public string UserName
        {
            get { return _UserName; }
            set { _UserName = value; }
        }
        private string _Password;
        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return _Password; }
            set { _Password = value; }
        }
        private string _NickName;
        /// <summary>
        /// 昵称
        /// </summary>
        public string NickName
        {
            get { return _NickName; }
            set { _NickName = value; }
        }
        private bool _Sex;
        /// <summary>
        /// 性别
        /// </summary>
        public bool Sex
        {
            get { return _Sex; }
            set { _Sex = value; }
        }
        public string SexStr
        {
            get { return _Sex ? "" : ""; }
        }
    
        private DateTime _Birthday;
        /// <summary>
        /// 生日
        /// </summary>
        public DateTime Birthday
        {
            get { return _Birthday; }
            set { _Birthday = value; }
        }
    
        public string BirthdayStr
        {
            get { return _Birthday.ToString("yyyy年MM月dd日"); }
        }
    
    
        private string _Nation;
        /// <summary>
        /// 民族
        /// </summary>
        public string Nation
        {
            get { return _Nation; }
            set { _Nation = value; }
        }
    
        public string NationName
        {
            get { return new NationDA().Select(this._Nation).NationName; }
    
        }
    
        /// <summary>
        /// 扩展年龄
        /// </summary>
        public string Age
        {
            get { return (DateTime.Now.Year - this._Birthday.Year).ToString(); }
        }
    Users
    /// <summary>
    /// UsersDA 的摘要说明
    /// </summary>
    public class UsersDA
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        public UsersDA()
        {
            conn = new SqlConnection("server=.;database=Data0617;user=sa;pwd=128712jdhlys");
            cmd = conn.CreateCommand();
        }
        public List<Users> Select()
        {
            List<Users> list = new List<Users>();
            cmd.CommandText = "select * from Users";
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    
                    Users da = new Users();
                    da.UserName = dr[0].ToString();
                    da.Password = dr[1].ToString();
                    da.NickName = dr[2].ToString();
                    da.Sex = Convert.ToBoolean(dr["Sex"]);
                    da.Birthday = Convert.ToDateTime(dr["Birthday"]);
                    da.Nation = dr["Nation"].ToString();
                    list.Add(da);
                }
            }
            conn.Close();
            return list;
        }
    UsersDA

    前台web代码:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <style type="text/css">
            #tb1 {
                 100%;
                background-color: navy;
                text-align: center;
            }
    
            #tr_head {
                color: white;
            }
    
            .tr_Item {
                background-color: white;
            }
    
            .tr_Item2 {
                background-color: #e0e0e0;
            }
        </style>
    
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:Repeater ID="Repeater1" runat="server">
                <HeaderTemplate>
                    <table id="tb1">
                        <tr id="tr_head">
                            <td>账号</td>
                            <td>密码</td>
                            <td>昵称</td>
                            <td>性别</td>
                            <td>生日</td>
                            <td>年龄</td>
                            <td>民族</td>
                        </tr>                   
                </HeaderTemplate>
                <ItemTemplate>
                    <tr class="tr_Item" >
                        <td><%#Eval("UserName") %></td>
                        <td><%#Eval("Password") %></td>
                        <td><%#Eval("NickName") %></td>
                        <td><%#Eval("SexStr") %></td>
                        <td><%#Eval("BirthdayStr") %></td>
                        <td><%#Eval("Age") %></td>
                        <td><%#Eval("NationName") %></td>
                    </tr>
                </ItemTemplate>
                <FooterTemplate >
                    </table>
                </FooterTemplate>
            </asp:Repeater>
        </form>
    </body>
    </html>
    前台

    后台cs代码:

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Repeater1.DataSource = new UsersDA().Select();
                Repeater1.DataBind();
            }
        }
    }
    后台

    效果图:


    三、预警显示

          比如:库存预警,某个物品少于某个数量的时候,改变其数据颜色等。

          方法:通过某个属性值判断后,将某条数据的样式进行更改。

                   通过属性扩展的方式,写一个返回string类型的属性,返回的是CSS样式表样式,为了让大家知道,属性值不一定非得是展示用。

    例3:运用上一个例题2,要求年龄超过14岁,预警显示为红色。

    Users实体类,属性扩展:

    /// <summary>
        /// 扩展预警属性
        /// </summary>
        public string Red
        {
            get
            {
                string end = "";
                if (Convert.ToInt32(Age) >= 15)
                {
                    end = "background-color:red;";
                }
                return end;
            }
        }
    Red属性扩展

    前台web更改位置:

     <ItemTemplate>
                    <tr class="tr_Item" style="<%#Eval("Red") %>" >
                        <td><%#Eval("UserName") %></td>
                        <td><%#Eval("Password") %></td>
                        <td><%#Eval("NickName") %></td>
                        <td><%#Eval("SexStr") %></td>
                        <td><%#Eval("BirthdayStr") %></td>
                        <td><%#Eval("Age") %></td>
                        <td><%#Eval("NationName") %></td>
                    </tr>
                </ItemTemplate>
    前台更改

    其他不变,效果显示:


    四、光棒效果

          意思是,当鼠标放上的时候,改变其属性,比如:背景色,边框颜色,边框样式等

          方法:js代码实现,用到两个事件,分别是:onmouseover(鼠标放上)和onmouseout(鼠标离开)

    例:同样运用上个例题2

    1、不论是正常显示的还是预警显示的,当鼠标放上时,背景色变为黄色;鼠标离开,回复原来的颜色。

    前端代码:

    </style>
        <script >
            window.onload=function(){
                var items = document.getElementsByClassName("tr_Item");
                var oldColor = "";注释:存放原来的背景色
                for (var i = 0; i < items.length; i++) {
                    items[i].onmouseover = function () {
                        oldColor = this.style.backgroundColor;
                        this.style.backgroundColor = "yellow";
                    }
                    items[i].onmouseout = function () {
                        this.style.backgroundColor = oldColor;
                    }
                }
            }
        </script>
    </head>
    <body>
    View Code

    注:效果不好截图,感兴趣的可以写写运行看看。
    2、除预警显示红色不变外,当鼠标放上时,背景色变为黄色;鼠标离开,回复原来的颜色。

    前端代码:

     </style>
        <script >
            window.onload=function(){
                var items = document.getElementsByClassName("tr_Item");            
                for (var i = 0; i < items.length; i++) {
                    if (items[i].style.backgroundColor != Red) {
                        items[i].onmouseover = function () {
                            this.style.backgroundColor = "yellow";
                        }
                        items[i].onmouseout = function () {
                            this.style.backgroundColor = oldColor;
                        }
                    }
                }
            }
        </script>
    View Code

    注:效果不好截图,感兴趣的可以写写运行看看。


    五、非表格信息展示(比如:京东或者淘宝上,各个商品有规律的一格一格的排列展示)
          方法:1、纯HTML+css+js制作

                   2、添加Repeater控件,将数据绑定展示

    例:同样运用上面的例题2

    前台代码:

    <body>
        <form id="form1" runat="server">
            <div id="top"></div>
            <div id="main">
                <asp:Repeater ID="Repeater1" runat="server">
                    <ItemTemplate>
                        <div class="item">
                            <%#Eval("UserName") %><br />
                            <%#Eval("PassWord") %><br />
                            <%#Eval("NickName") %>
                        </div>
                    </ItemTemplate>
                </asp:Repeater>           
            </div>
            <div id="bottom"></div>
            <script type="text/javascript">
                var items = document.getElementsByClassName("item");
                var hei = items[0].offsetHeight;
                document.getElementById("main").style.height = (hei + 10) * Math.ceil(items.length / 4) + 'px';
            </script>
    前台

    css样式表代码:

    * {
        padding: 0px;
        margin: 0px;
    }
    
    #top {
        position: relative;
         100%;
        height: 70px;
        background-color: navy;
    }
    
    #main {
        position: relative;
         80%;
        left: 10%;
        height: auto;
    
    }
    
    .item {
        position: relative;
         23%;
        margin:5px 1%;
        height: 200px;
        background-color: red;
        float:left;
    }
    
    
    #bottom {
        position: relative;
         100%;
        height: 70px;
        background-color: black;
    }
    css

    注:后台数据绑定和连接数据库一样
    效果显示:


    六、Repeater控件的事件处理

          Repeater控件有以下事件:     
                  ● DataBinding : Repeater控件绑定到数据源时触发      
                  ● ItemCommand : Repeater控件中的子控件触发事件时触发      
                  ● ItemCreated : 创建Repeater每个项目时触发 
                  ● ItemDataBound : Repeater控件的每个项目绑定数据时触发     

    后注:整理不当,有误的地方还请告知,相互学习。且此控件在web中非常好用,相当灵活

  • 相关阅读:
    二级分类的清空
    解决django.core.exceptions.ImproperlyConfigured: Cannot import 'book.apps.users'. Check that 'apps.users.apps.UsersConfig.name' is correct.
    解决使用manage.py task迁移数据库时遇到的问题:django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
    下拉框:value的作用例子
    解决django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
    pipenv install 安装虚拟OSError: Command E:\virtual_workshop\...T\Scripts\python.exe setuptools pip wheel failed with error code 2
    解决爬虫爬取豆瓣图片加载限制403
    select选择框选择后,可以直接使用:value的值
    (笔记)MQTT简介
    (笔记)进程间通信的六种方式
  • 原文地址:https://www.cnblogs.com/H2921306656/p/5898411.html
Copyright © 2020-2023  润新知