詳解ASP.NET數(shù)據(jù)綁定操作中Repeater控件的用法

一、綁定控件之Repeater
.NET封裝了多種數(shù)據(jù)綁定控件,諸如GridView、DataList等但該篇文章將會從Repeater入手,因為Repeater只提供了基本的數(shù)據(jù)綁定模板,沒有內(nèi)置其它分頁等功能,所以它是最原始的數(shù)據(jù)綁定控件,只要能夠熟練運用Repeater控件其它的綁定控件也就很簡單了。
1、Repeater簡介
Repeater 控件是基本模板化數(shù)據(jù)列表。 它不像GridView控件一樣能夠可視化的設(shè)計格式或樣式,因此開發(fā)時在控件模板中必須顯式聲明所有格式、格式和樣式標記。另外Repeater控件沒有內(nèi)置選擇、排序、編輯、分頁等功能,它只提供了基本的數(shù)據(jù)綁定,但是它為開發(fā)人員提供了ItemCommand 事件,該事件支持在控件中收發(fā)命令。
想要綁定數(shù)據(jù),模板是必不可少的,Repeater控件同樣支持數(shù)據(jù)模板,而且還可以在模板中添加想要的標簽,它主要用法如下圖:

Note:每個 Repeater 控件必須定義 ItemTemplate。

二、控件使用技巧
上文講解了Repeater基本的使用方法及它的一些基本特性,接下來做幾個經(jīng)典的示例來運用Repeater控件。
1、數(shù)據(jù)綁定之刪除、編輯
該示例將會使用Asp.net的前臺和后臺結(jié)合來實現(xiàn)顯示數(shù)據(jù),并能夠編輯和刪除數(shù)據(jù)。
刪除頁面:

編輯頁面:

前臺代碼:在單擊編輯按鈕后將會進入編輯頁面,頁面是由兩個Panel控件來控制,通過傳遞ID號的方式判斷顯示的是編輯頁面還是刪除頁面,另外前臺代碼通過設(shè)置控件的CommandArgument屬性來傳遞后臺所需要判斷的id號。
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="userRepeat" runat="server" OnItemCommand="userRepeat_ItemCommand" OnItemDataBound="userRepeat_ItemDataBound">
<HeaderTemplate>
<table border="1" style="width:1000px;text-align:center;border-collapse:collapse;">
<thead style="background-color:red;">
<tr>
<th>ID</th>
<th>內(nèi)容</th>
<th>操作</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<asp:Panel ID="plItem" runat="server">
<tr>
<td><asp:Label runat="server" ID="lblID" Text='<%#Eval("id") %>'></asp:Label></td>
<td><%#Eval("name") %></td>
<td>
<asp:LinkButton ID="lbtEdit" CommandName="Edit" CommandArgument='<%#Eval("id") %>' runat="server">編輯</asp:LinkButton>
<asp:LinkButton ID="lbtDelete" CommandName="Delete" CommandArgument='<%#Eval("id") %>' runat="server">刪除</asp:LinkButton>
</td>
</tr>
</asp:Panel>
<asp:Panel ID="plEdit" runat="server">
<tr>
<td><asp:Label runat="server" ID="Label1" Text='<%#Eval("id") %>'></asp:Label></td>
<td><asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox></td>
<td>
<asp:LinkButton ID="lbtCancel" CommandName="Cancel" CommandArgument='<%#Eval("id") %>' runat="server">取消</asp:LinkButton>
<asp:LinkButton ID="lbtUpdate" CommandName="Update" CommandArgument='<%#Eval("id") %>' runat="server">更新</asp:LinkButton>
</td>
</tr>
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
后臺代碼:在后臺代碼中很重要的兩個事件是ItemCommand和ItemDataBound,其中ItemCommand負責接收前臺傳進來的按鈕命令,根據(jù)命令的參數(shù)來設(shè)置后臺傳遞的id,并在ItemDataBound中來驗證id判斷切換顯示Panel。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class EditPage : System.Web.UI.Page
{
private int id = 0; //保存指定行操作所在的ID號
/// <summary>
/// 窗體加載時綁定數(shù)據(jù)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.DataBindToRepeater();//將數(shù)據(jù)綁定到Repeater控件上
}
}
/// <summary>
/// 將數(shù)據(jù)源綁定Repeater控件上
/// </summary>
private void DataBindToRepeater() {
//使用using語句進行數(shù)據(jù)庫連接
using (SqlConnection sqlCon=new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
{
sqlCon.Open(); //打開數(shù)據(jù)庫連接
SqlCommand sqlcom = new SqlCommand(); //創(chuàng)建數(shù)據(jù)庫命令對象
sqlcom.CommandText = "select * from match"; //為命令對象指定執(zhí)行語句
sqlcom.Connection = sqlCon; //為命令對象指定連接對象
this.userRepeat.DataSource = sqlcom.ExecuteReader(); //為Repeater對象指定數(shù)據(jù)源
this.userRepeat.DataBind(); //綁定數(shù)據(jù)源
}
}
/// <summary>
/// Repeater控件命令事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
protected void userRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//獲取命令文本,判斷發(fā)出的命令為何種類型,根據(jù)命令類型調(diào)用事件
if (e.CommandName=="Edit") //編輯命令
{
id = int.Parse(e.CommandArgument.ToString()); //獲取命令I(lǐng)D號
}
else if (e.CommandName=="Cancel") //取消更新命令
{
id = -1;
}
else if(e.CommandName=="Delete") //刪除行內(nèi)容命令
{
id = int.Parse(e.CommandArgument.ToString()); //獲取刪除行的ID號
//刪除選定的行,并重新指定綁定操作
this.DeleteRepeater(id);
}
else if (e.CommandName == "Update") //更新行內(nèi)容命令
{
//獲取更新行的內(nèi)容和ID號
string strText = ((TextBox)e.Item.FindControl("txtName")).Text.Trim();
int intId=int.Parse(((Label)e.Item.FindControl("lblID")).Text);
//更新Repeater控件的內(nèi)容
this.UpdateRepeater(strText,intId);
}
//重新綁定控件上的內(nèi)容
this.DataBindToRepeater();
}
/// <summary>
/// 刪除行內(nèi)容
/// </summary>
/// <param name="intId">刪除行所在內(nèi)容的ID</param>
private void DeleteRepeater(int intId) {
using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
{
sqlCon.Open(); //打開數(shù)據(jù)庫連接
SqlCommand sqlcom = new SqlCommand(); //創(chuàng)建數(shù)據(jù)庫命令對象
sqlcom.CommandText = "delete from match where id=@id"; //為命令對象指定執(zhí)行語句
sqlcom.Connection = sqlCon; //為命令對象指定連接對象
//創(chuàng)建參數(shù)集合,并向sqlcom中添加參數(shù)集合
SqlParameter sqlParam = new SqlParameter("@id", intId);
sqlcom.Parameters.Add(sqlParam);
sqlcom.ExecuteNonQuery(); //指定更新語句
}
}
/// <summary>
/// 更新Repeater控件中的內(nèi)容
/// </summary>
/// <param name="strText">修改后的內(nèi)容</param>
/// <param name="intId">內(nèi)容所在行的ID號</param>
private void UpdateRepeater(string strText,int intId) {
using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
{
sqlCon.Open(); //打開數(shù)據(jù)庫連接
SqlCommand sqlcom = new SqlCommand(); //創(chuàng)建數(shù)據(jù)庫命令對象
sqlcom.CommandText = "update match set name=@str where id=@id"; //為命令對象指定執(zhí)行語句
sqlcom.Connection = sqlCon; //為命令對象指定連接對象
//創(chuàng)建參數(shù)集合,并向sqlcom中添加參數(shù)集合
SqlParameter[] sqlParam = { new SqlParameter("@str", strText), new SqlParameter("@id", intId) };
sqlcom.Parameters.AddRange(sqlParam);
sqlcom.ExecuteNonQuery(); //指定更新語句
}
}
/// <summary>
/// Repeater控件數(shù)據(jù)綁定時發(fā)生的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void userRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//判斷Repeater控件中的數(shù)據(jù)是否是綁定的數(shù)據(jù)源,如果是的話將會驗證是否進行了編輯操作
//ListItemType 枚舉表示在一個列表控件可以包括,例如 DataGrid、 DataList和 Repeater 控件的不同項目。
if (e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
//獲取綁定的數(shù)據(jù)源,這里要注意上面使用sqlReader的方法來綁定數(shù)據(jù)源,所以下面使用的DbDataRecord方法獲取的
//如果綁定數(shù)據(jù)源是DataTable類型的使用下面的語句就會報錯.
System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord)e.Item.DataItem;
//DataTable類型的數(shù)據(jù)源驗證方式
//System.Data.DataRowView record = (DataRowView)e.Item.DataItem;
//判斷數(shù)據(jù)源的id是否等于現(xiàn)在的id,如果相等的話證明現(xiàn)點擊了編輯觸發(fā)了userRepeat_ItemCommand事件
if (id == int.Parse(record["id"].ToString()))
{
((Panel)e.Item.FindControl("plItem")).Visible = false;
((Panel)e.Item.FindControl("plEdit")).Visible = true;
}
else
{
((Panel)e.Item.FindControl("plItem")).Visible = true;
((Panel)e.Item.FindControl("plEdit")).Visible = false;
}
}
}
}
}
2、分頁--PageDataSource
前臺代碼:使用原始的html文本,并添加了一個Literal標簽,用來動態(tài)添加并指定html標簽。
頁面截圖:

<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">
.pageBar
{
margin-top: 10px;
}
.pageBar a
{
color: #333;
font-size: 12px;
margin-right: 10px;
padding: 4px;
border: 1px solid #ccc;
text-decoration: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate>
<table border="1" cellpadding="0" cellspacing="0" style="width:1006px;border-collapse:collapse; text-align:center;">
<tr>
<th style="background-color:red">ID</th>
<th style="background-color:red">內(nèi)容</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Label ID="lblId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"id") %>' ></asp:Label></td>
<td><%# DataBinder.Eval(Container.DataItem,"name") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
<div class="pageBar">
<asp:Literal ID="ltlPageBar" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
后臺代碼:Repeater控件的數(shù)據(jù)源是PagedDataSource對象,在頁面加載時為該對象動態(tài)指定了分頁的屬性,并使用Literal標簽來動態(tài)指定每個標簽跳轉(zhuǎn)頁的鏈接。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class PageDemo : System.Web.UI.Page
{
private string id = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//設(shè)置當前頁的索引
int pageIndex = 1;
try
{
//獲取當前索要跳轉(zhuǎn)頁的索引號
pageIndex = Convert.ToInt32(Request.QueryString["Page"]);
//如果是第0頁將會跳轉(zhuǎn)入第1頁
if (pageIndex <= 0)
{
pageIndex = 1;
}
}
catch
{
pageIndex = 1;
}
DataTable dt = this.GetDataTable(); //獲取綁定的數(shù)據(jù)表
PagedDataSource pds = new PagedDataSource(); //創(chuàng)建分頁數(shù)據(jù)源對象
pds.DataSource = dt.DefaultView; //為數(shù)據(jù)源對象設(shè)置數(shù)據(jù)源
pds.AllowPaging = true; //對象允許分頁
pds.PageSize = 2; //設(shè)置對象每頁顯示的大小
pds.CurrentPageIndex = pageIndex - 1; //設(shè)置數(shù)據(jù)源的當前頁
//向Repeater控件上綁定分頁數(shù)據(jù)源控件
this.Repeater1.DataSource = pds;
this.Repeater1.DataBind();
//使用Literal標簽來動態(tài)指定每個標簽跳轉(zhuǎn)頁的鏈接
ltlPageBar.Text = this.GetPageBar(pds);
}
}
/// <summary>
/// 獲取每個標簽上的跳轉(zhuǎn)頁的鏈接地址
/// </summary>
/// <param name="pds">分頁數(shù)據(jù)源對象</param>
/// <returns>分頁操作按鈕的html文本</returns>
private string GetPageBar(PagedDataSource pds)
{
string pageBar = string.Empty; //聲明頁面標簽文本
int currentPageIndex = pds.CurrentPageIndex + 1; //獲取當前頁索引
//判斷首頁的鏈接頁面
if (currentPageIndex == 1) //如果該頁為第一頁,則證明它為首頁
{
pageBar += "<a href=\"javascript:void(0)\">首頁</a>";
}
else
{
//如果不是首頁,首頁鏈接的地址將會為1
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=1\">首頁</a>";
}
//判斷上一頁鏈接的地址
if ((currentPageIndex - 1) < 1) //如果上一頁小于1則鏈接到第一頁
{
pageBar += "<a href=\"javascript:void(0)\">上一頁</a>";
}
else
{
//如果上一頁地址不是1將會鏈接到上一頁
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex - 1) + "\">上一頁</a>";
}
//指定下一頁的鏈接地址
if ((currentPageIndex + 1) > pds.PageCount)
{
//如果下一頁的地址大于總頁數(shù),將會連接到首頁
pageBar += "<a href=\"javascript:void(0)\">下一頁</a>";
}
else
{
//否則的話鏈接到下一頁
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex + 1) + "\">下一頁</a>";
}
//指定末頁的鏈接地址
if (currentPageIndex == pds.PageCount)
{
pageBar += "<a href=\"javascript:void(0)\">末頁</a>";
}
else
{
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + pds.PageCount + "\">末頁</a>";
}
return pageBar; //返回html文本
}
/// <summary>
/// 獲取數(shù)據(jù)源,重新鏈接數(shù)據(jù)
/// </summary>
/// <returns>DataTable,數(shù)據(jù)源</returns>
private DataTable GetDataTable()
{
DataTable dt = new DataTable(); //創(chuàng)建數(shù)據(jù)庫表
using (SqlConnection con = new SqlConnection("server=.;DataBase=MyBlog;uid=sa;pwd=1;"))
{
con.Open(); //打開數(shù)據(jù)庫鏈接
SqlCommand sqlCom = new SqlCommand(); //聲明并創(chuàng)建數(shù)據(jù)庫命令集
StringBuilder sqlStr = new StringBuilder(); //聲明sql語句
sqlStr.Append("select * from match"); //獲取sql語句
sqlCom.CommandText = sqlStr.ToString(); //為sqlcommand對象指定sql語句
sqlCom.Connection = con; //為sqlcommand對象指定鏈接對象
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom); //聲明數(shù)據(jù)庫適配器
SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlDa);
sqlDa.Fill(dt); //填充表
}
return dt;
}
}
}
結(jié)語
文章主要介紹了Repeater控件的基本使用方法,并通過兩個示例來更深一步的學習了Repeater控件的使用。雖然Repeater控件封裝的操作較少,但它是最基礎(chǔ)的數(shù)據(jù)綁定控件,另外可以通過使用其它控件來彌補Repeater控件的不足,如可以通過使用PagedataSource類來實現(xiàn)數(shù)據(jù)的分頁。文章寫到這里并沒有結(jié)束,下篇文章將會著重討論ListView。
- 詳解ASP.NET-----Repeater數(shù)據(jù)控件的用法總結(jié)
- ASP.NET數(shù)據(jù)綁定之Repeater控件
- asp.net中使用 Repeater控件拖拽實現(xiàn)排序并同步數(shù)據(jù)庫字段排序
- asp.net使用Repeater控件中的全選進行批量操作實例
- ASP.NET中repeater控件用法實例
- asp.net Repeater控件的說明及詳細介紹及使用方法
- asp.net下Repeater使用 AspNetPager分頁控件
- asp.net 遍歷repeater中的控件的幾種方式
- ASP.NET實現(xiàn)Repeater控件的數(shù)據(jù)綁定
相關(guān)文章
MVC 5 第二章 MVC5應用程序項目結(jié)構(gòu)
通過本章學習,你將了解到一個MVC 5應用程序的項目組成以及項目文件的相關(guān)信息,從而更好地架構(gòu)設(shè)計出自己的項目結(jié)構(gòu)。2014-06-06
ASP.NET實現(xiàn)根據(jù)IP獲取省市地址的方法
這篇文章主要介紹了ASP.NET實現(xiàn)根據(jù)IP獲取省市地址的方法,主要基于QQwry.dat純真IP數(shù)據(jù)庫來實現(xiàn)這一功能,非常實用,需要的朋友可以參考下2014-10-10
asp.net URL中包含中文參數(shù)造成亂碼的解決方法
中文亂碼一直以來是WEB開發(fā)中比較常見的問題之一,對于初學者來說,各種各樣的編碼方式可能會有點不適應,本篇文章并不講述這些編碼,而是把自己遇到的一個小問題以及該問題的解決之法說明一下,希望對大家有用。2010-03-03
GridView使用CommandField刪除列實現(xiàn)刪除時提示確認框
在.net2005提供的GridView中我們可以直接添加一個CommandField刪除列完后在它的RowDeleting事件中完成刪除2013-09-09
ASP.NET MVC DropDownList數(shù)據(jù)綁定及使用詳解
DropDownList 控件用于創(chuàng)建下拉列表。DropDownList 控件中的每個可選項都是由 ListItem 元素定義的!該控件支持數(shù)據(jù)綁定2012-12-12

