zoukankan      html  css  js  c++  java
  • Repeater控件用法

    在ASP.NET中最常用的数据绑定方法就是Repeater了,不仅因为使用简单,而且Repeater轻量级,没有VIEWSTATE,深受开发者亲睐。本片博客就来介绍Repeater的使用方法和注意事项。

    一、准备数据

    在数据库中创建一张表,具体的sql脚本如下:

     

    create database Test

    go

    create table students

    (

        ID int identity(1,1) primary key,

        [Name] nvarchar(20) not null,

        Sex int not null -- 1:male 0:female

    )

     

    insert into students(Name,sex) values('Frank',1);

    insert into students(Name,sex) values('Caroline',0);

    insert into students(Name,sex) values('Tom',1);

    insert into students(Name,sex) values('Jack',1);

    创建后的效果如下图所示:

    image

     

    二、在项目中测试

    在Visual Studio中新建一个WebApplication,进行测试。

    image

    在后台.cs文件中的代码如下:

    protected void Page_Load(object sender, EventArgs e)

    {

        string connStr = @"server=.\SQLEXPRESS;database=Test;uid=sa;pwd=123456";

        SqlConnection conn = new SqlConnection(connStr);

        try

        {

            conn.Open();

            SqlCommand cmd = new SqlCommand("select * from students", conn);

            SqlDataReader sdr = cmd.ExecuteReader();

            DataTable dt = new DataTable();

            dt.Load(sdr);

            rep.DataSource = dt;

            rep.DataBind();

        }

        catch (Exception ex)

        {

            throw ex;

        }      

    }

     

    前台页面放一个Repeater控件,添加一个<ItemTemplate>模板,如下:

    <asp:Repeater ID="rep" runat="server" onitemdatabound="rep_ItemDataBound">

        <ItemTemplate>

            <%#Eval("ID") %><%#Eval("Name") %><%#Eval("Sex") %>

            <br />

        </ItemTemplate>

    </asp:Repeater>

    用Eval(string expression)表达式绑定字段,进行展示。运行结果如图:

    image

    我们需要把表示性别的1和0转换成有意思的文字让人看。所以需要在Repeater绑定之前做一些事情。

    具体代码如下:

     

    // 绑定之前显示男女

    protected void rep_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)

    {

        DataRowView drv = (DataRowView)e.Item.DataItem;

        Label lbl = (Label)e.Item.FindControl("lblSex");

        if (drv["Sex"].ToString() == "1")

        {

            lbl.Text = "";

        }

        else

        {

            lbl.Text = "";

        }

    }

    页面只需稍作更改即可:

    <asp:Repeater ID="rep" runat="server" onitemdatabound="rep_ItemDataBound">

        <ItemTemplate>

            <%#Eval("ID") %><%#Eval("Name") %><asp:Label ID="lblSex" runat="server" Text=""></asp:Label>

            <br />

        </ItemTemplate>

    </asp:Repeater>

    最后运行效果如图所示:

    image

  • 相关阅读:
    R-CNN算法中NMS的具体做法
    Spring之Environment
    Spring之Aware
    每晚夜里自我独行,随处荡,多冰冷,以往为了自我挣扎
    Java 反射机制
    Java string String
    Java int Integer
    Java final
    Java toString()方法
    Java Enum
  • 原文地址:https://www.cnblogs.com/fanyong/p/2625796.html
Copyright © 2011-2022 走看看