Repeater控件用法

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

一、准备数据

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

 

 1 create database Test
 2 
 3 go
 4 
 5 create table students
 6 
 7 (
 8 
 9     ID int identity(1,1) primary key,
10 
11     [Name] nvarchar(20) not null,
12 
13     Sex int not null -- 1:male 0:female
14 
15 )
16 
17  
18 
19 insert into students(Name,sex) values('Frank',1);
20 
21 insert into students(Name,sex) values('Caroline',0);
22 
23 insert into students(Name,sex) values('Tom',1);
24 
25 insert into students(Name,sex) values('Jack',1);

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

二、在项目中测试

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

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

 1 protected void Page_Load(object sender, EventArgs e)
 2 
 3 {
 4 
 5     string connStr = @"server=.\SQLEXPRESS;database=Test;uid=sa;pwd=123456";
 6 
 7     SqlConnection conn = new SqlConnection(connStr);
 8 
 9     try
10 
11     {
12 
13         conn.Open();
14 
15         SqlCommand cmd = new SqlCommand("select * from students", conn);
16 
17         SqlDataReader sdr = cmd.ExecuteReader();
18 
19         DataTable dt = new DataTable();
20 
21         dt.Load(sdr);
22 
23         rep.DataSource = dt;
24 
25         rep.DataBind();
26 
27     }
28 
29     catch (Exception ex)
30 
31     {
32 
33         throw ex;
34 
35     }       
36 
37 }

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

<asp:RepeaterID="rep"runat="server"onitemdatabound="rep_ItemDataBound">

    <ItemTemplate>

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

        <br/>

    </ItemTemplate>

</asp:Repeater>

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

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

具体代码如下:

 

 1 // 绑定之前显示男女
 2 
 3 protected void rep_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
 4 
 5 {
 6 
 7     DataRowView drv = (DataRowView)e.Item.DataItem;
 8 
 9     Label lbl = (Label)e.Item.FindControl("lblSex");
10 
11     if (drv["Sex"].ToString() == "1")
12 
13     {
14 
15         lbl.Text = "";
16 
17     }
18 
19     else
20 
21     {
22 
23         lbl.Text = "";
24 
25     }
26 
27 }

页面只需稍作更改即可:

<asp:RepeaterID="rep"runat="server"onitemdatabound="rep_ItemDataBound">

    <ItemTemplate>

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

        <br/>

    </ItemTemplate>

</asp:Repeater>

最后运行效果如图所示:

 

 

 

 

 

 

 

 

 

posted @ 2015-10-12 15:36  陌钰陌城  Views(161)  Comments(0Edit  收藏  举报