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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM