数据绑定控件之Repeater

向右看齐 2021-07-04 21:02 573阅读 0赞

要不是工作所迫,谁愿意用已没落的技术。

引言

前几篇的文章在说AJAX的内容,利用AJAX技术能够开发出高效运行的网站应用程序,不过在进行B/S项目开发时只拥有AJAX技术是远远不够的,踏入到B/S要学的东西会更多,但相较C/S的复杂逻辑结构来说B/S在开发时还是很简单的。

在开发B/S项目时,常常会用到数据绑定控件,.NET平台已经对这些控件进行了良好的封装,只要稍有经验的程序猿很快就能够上手使用这些数据控件,所以接下来的几篇文章将会讨论数据控件,首先将会从数据控件的细节入手讨论ListView、GridView、Repeater、DataList控件的基本使用方法,并在会后系列文章的最后对这几个控件进行综合性的分析总结。
在这里插入图片描述

一、绑定控件之Repeater

.NET封装了多种数据绑定控件,诸如GridView、DataList等但该篇文章将会从Repeater入手,因为Repeater只提供了基本的数据绑定模板,没有内置其它分页等功能,所以它是最原始的数据绑定控件,只要能够熟练运用Repeater控件其它的绑定控件也就很简单了。

1、Repeater简介

Repeater 控件是基本模板化数据列表。 它不像GridView控件一样能够可视化的设计格式或样式,因此开发时在控件模板中必须显式声明所有格式、格式和样式标记。另外Repeater控件没有内置选择、排序、编辑、分页等功能,它只提供了基本的数据绑定,但是它为开发人员提供了ItemCommand 事件,该事件支持在控件中收发命令。

想要绑定数据,模板是必不可少的,Repeater控件同样支持数据模板,而且还可以在模板中添加想要的标签,它主要用法如下图:
在这里插入图片描述
Note:每个 Repeater 控件必须定义 ItemTemplate

二、控件使用技巧

上文讲解了Repeater基本的使用方法及它的一些基本特性,接下来做几个经典的示例来运用Repeater控件。

1、数据绑定之删除、编辑
该示例将会使用Asp.net的前台和后台结合来实现显示数据,并能够编辑和删除数据。
删除页面:
在这里插入图片描述
编辑页面:
在这里插入图片描述
前台代码:在单击编辑按钮后将会进入编辑页面,页面是由两个Panel控件来控制,通过传递ID号的方式判断显示的是编辑页面还是删除页面,另外前台代码通过设置控件的CommandArgument属性来传递后台所需要判断的id号。

  1. <body>
  2. <form id="form1" runat="server">
  3. <div>
  4. <asp:Repeater ID="userRepeat" runat="server" OnItemCommand="userRepeat_ItemCommand" OnItemDataBound="userRepeat_ItemDataBound">
  5. <HeaderTemplate>
  6. <table border="1" style="width:1000px;text-align:center;border-collapse:collapse;">
  7. <thead style="background-color:red;">
  8. <tr>
  9. <th>ID</th>
  10. <th>内容</th>
  11. <th>操作</th>
  12. </tr>
  13. </thead>
  14. </HeaderTemplate>
  15. <ItemTemplate>
  16. <asp:Panel ID="plItem" runat="server">
  17. <tr>
  18. <td><asp:Label runat="server" ID="lblID" Text='<%#Eval("id") %>'></asp:Label></td>
  19. <td><%#Eval("name") %></td>
  20. <td>
  21. <asp:LinkButton ID="lbtEdit" CommandName="Edit" CommandArgument='<%#Eval("id") %>' runat="server">编辑</asp:LinkButton>
  22. <asp:LinkButton ID="lbtDelete" CommandName="Delete" CommandArgument='<%#Eval("id") %>' runat="server">删除</asp:LinkButton>
  23. </td>
  24. </tr>
  25. </asp:Panel>
  26. <asp:Panel ID="plEdit" runat="server">
  27. <tr>
  28. <td><asp:Label runat="server" ID="Label1" Text='<%#Eval("id") %>'></asp:Label></td>
  29. <td><asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox></td>
  30. <td>
  31. <asp:LinkButton ID="lbtCancel" CommandName="Cancel" CommandArgument='<%#Eval("id") %>' runat="server">取消</asp:LinkButton>
  32. <asp:LinkButton ID="lbtUpdate" CommandName="Update" CommandArgument='<%#Eval("id") %>' runat="server">更新</asp:LinkButton>
  33. </td>
  34. </tr>
  35. </asp:Panel>
  36. </ItemTemplate>
  37. <FooterTemplate>
  38. </table>
  39. </FooterTemplate>
  40. </asp:Repeater>
  41. </div>
  42. </form>
  43. </body>

后台代码:在后台代码中很重要的两个事件是ItemCommandItemDataBound,其中ItemCommand负责接收前台传进来的按钮命令,根据命令的参数来设置后台传递的id,并在ItemDataBound中来验证id判断切换显示Panel

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Web;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. namespace WebApplication4
  9. {
  10. public partial class EditPage : System.Web.UI.Page
  11. {
  12. private int id = 0; //保存指定行操作所在的ID号
  13. /// <summary>
  14. /// 窗体加载时绑定数据
  15. /// </summary>
  16. /// <param name="sender"></param>
  17. /// <param name="e"></param>
  18. protected void Page_Load(object sender, EventArgs e)
  19. {
  20. if (!Page.IsPostBack)
  21. {
  22. this.DataBindToRepeater();//将数据绑定到Repeater控件上
  23. }
  24. }
  25. /// <summary>
  26. /// 将数据源绑定Repeater控件上
  27. /// </summary>
  28. private void DataBindToRepeater() {
  29. //使用using语句进行数据库连接
  30. using (SqlConnection sqlCon=new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
  31. {
  32. sqlCon.Open(); //打开数据库连接
  33. SqlCommand sqlcom = new SqlCommand(); //创建数据库命令对象
  34. sqlcom.CommandText = "select * from match"; //为命令对象指定执行语句
  35. sqlcom.Connection = sqlCon; //为命令对象指定连接对象
  36. this.userRepeat.DataSource = sqlcom.ExecuteReader(); //为Repeater对象指定数据源
  37. this.userRepeat.DataBind(); //绑定数据源
  38. }
  39. }
  40. /// <summary>
  41. /// Repeater控件命令事件
  42. /// </summary>
  43. /// <param name="source"></param>
  44. /// <param name="e"></param>
  45. protected void userRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
  46. {
  47. //获取命令文本,判断发出的命令为何种类型,根据命令类型调用事件
  48. if (e.CommandName=="Edit") //编辑命令
  49. {
  50. id = int.Parse(e.CommandArgument.ToString()); //获取命令ID号
  51. }
  52. else if (e.CommandName=="Cancel") //取消更新命令
  53. {
  54. id = -1;
  55. }
  56. else if(e.CommandName=="Delete") //删除行内容命令
  57. {
  58. id = int.Parse(e.CommandArgument.ToString()); //获取删除行的ID号
  59. //删除选定的行,并重新指定绑定操作
  60. this.DeleteRepeater(id);
  61. }
  62. else if (e.CommandName == "Update") //更新行内容命令
  63. {
  64. //获取更新行的内容和ID号
  65. string strText = ((TextBox)e.Item.FindControl("txtName")).Text.Trim();
  66. int intId=int.Parse(((Label)e.Item.FindControl("lblID")).Text);
  67. //更新Repeater控件的内容
  68. this.UpdateRepeater(strText,intId);
  69. }
  70. //重新绑定控件上的内容
  71. this.DataBindToRepeater();
  72. }
  73. /// <summary>
  74. /// 删除行内容
  75. /// </summary>
  76. /// <param name="intId">删除行所在内容的ID</param>
  77. private void DeleteRepeater(int intId) {
  78. using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
  79. {
  80. sqlCon.Open(); //打开数据库连接
  81. SqlCommand sqlcom = new SqlCommand(); //创建数据库命令对象
  82. sqlcom.CommandText = "delete from match where id=@id"; //为命令对象指定执行语句
  83. sqlcom.Connection = sqlCon; //为命令对象指定连接对象
  84. //创建参数集合,并向sqlcom中添加参数集合
  85. SqlParameter sqlParam = new SqlParameter("@id", intId);
  86. sqlcom.Parameters.Add(sqlParam);
  87. sqlcom.ExecuteNonQuery(); //指定更新语句
  88. }
  89. }
  90. /// <summary>
  91. /// 更新Repeater控件中的内容
  92. /// </summary>
  93. /// <param name="strText">修改后的内容</param>
  94. /// <param name="intId">内容所在行的ID号</param>
  95. private void UpdateRepeater(string strText,int intId) {
  96. using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
  97. {
  98. sqlCon.Open(); //打开数据库连接
  99. SqlCommand sqlcom = new SqlCommand(); //创建数据库命令对象
  100. sqlcom.CommandText = "update match set name=@str where id=@id"; //为命令对象指定执行语句
  101. sqlcom.Connection = sqlCon; //为命令对象指定连接对象
  102. //创建参数集合,并向sqlcom中添加参数集合
  103. SqlParameter[] sqlParam = { new SqlParameter("@str", strText), new SqlParameter("@id", intId) };
  104. sqlcom.Parameters.AddRange(sqlParam);
  105. sqlcom.ExecuteNonQuery(); //指定更新语句
  106. }
  107. }
  108. /// <summary>
  109. /// Repeater控件数据绑定时发生的事件
  110. /// </summary>
  111. /// <param name="sender"></param>
  112. /// <param name="e"></param>
  113. protected void userRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
  114. {
  115. //判断Repeater控件中的数据是否是绑定的数据源,如果是的话将会验证是否进行了编辑操作
  116. //ListItemType 枚举表示在一个列表控件可以包括,例如 DataGrid、 DataList和 Repeater 控件的不同项目。
  117. if (e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
  118. {
  119. //获取绑定的数据源,这里要注意上面使用sqlReader的方法来绑定数据源,所以下面使用的DbDataRecord方法获取的
  120. //如果绑定数据源是DataTable类型的使用下面的语句就会报错.
  121. System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord)e.Item.DataItem;
  122. //DataTable类型的数据源验证方式
  123. //System.Data.DataRowView record = (DataRowView)e.Item.DataItem;
  124. //判断数据源的id是否等于现在的id,如果相等的话证明现点击了编辑触发了userRepeat_ItemCommand事件
  125. if (id == int.Parse(record["id"].ToString()))
  126. {
  127. ((Panel)e.Item.FindControl("plItem")).Visible = false;
  128. ((Panel)e.Item.FindControl("plEdit")).Visible = true;
  129. }
  130. else
  131. {
  132. ((Panel)e.Item.FindControl("plItem")).Visible = true;
  133. ((Panel)e.Item.FindControl("plEdit")).Visible = false;
  134. }
  135. }
  136. }
  137. }
  138. }

2、分页–PageDataSource
前台代码:使用原始的html文本,并添加了一个Literal标签,用来动态添加并指定html标签。

页面截图:
在这里插入图片描述

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  4. <title></title>
  5. <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>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:Repeater ID="Repeater1" runat="server" >
  11. <HeaderTemplate>
  12. <table border="1" cellpadding="0" cellspacing="0" style="width:1006px;border-collapse:collapse; text-align:center;">
  13. <tr>
  14. <th style="background-color:red">ID</th>
  15. <th style="background-color:red">内容</th>
  16. </tr>
  17. </HeaderTemplate>
  18. <ItemTemplate>
  19. <tr>
  20. <td><asp:Label ID="lblId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"id") %>' ></asp:Label></td>
  21. <td><%# DataBinder.Eval(Container.DataItem,"name") %></td>
  22. </tr>
  23. </ItemTemplate>
  24. <FooterTemplate>
  25. </table>
  26. </FooterTemplate>
  27. </asp:Repeater>
  28. </div>
  29. <div class="pageBar">
  30. <asp:Literal ID="ltlPageBar" runat="server"></asp:Literal>
  31. </div>
  32. </form>
  33. </body>
  34. </html>

后台代码:Repeater控件的数据源是PagedDataSource对象,在页面加载时为该对象动态指定了分页的属性,并使用Literal标签来动态指定每个标签跳转页的链接。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Text;
  6. using System.Web;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. namespace WebApplication4
  10. {
  11. public partial class PageDemo : System.Web.UI.Page
  12. {
  13. private string id = "";
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. if (!Page.IsPostBack)
  17. {
  18. //设置当前页的索引
  19. int pageIndex = 1;
  20. try
  21. {
  22. //获取当前索要跳转页的索引号
  23. pageIndex = Convert.ToInt32(Request.QueryString["Page"]);
  24. //如果是第0页将会跳转入第1页
  25. if (pageIndex <= 0)
  26. {
  27. pageIndex = 1;
  28. }
  29. }
  30. catch
  31. {
  32. pageIndex = 1;
  33. }
  34. DataTable dt = this.GetDataTable(); //获取绑定的数据表
  35. PagedDataSource pds = new PagedDataSource(); //创建分页数据源对象
  36. pds.DataSource = dt.DefaultView; //为数据源对象设置数据源
  37. pds.AllowPaging = true; //对象允许分页
  38. pds.PageSize = 2; //设置对象每页显示的大小
  39. pds.CurrentPageIndex = pageIndex - 1; //设置数据源的当前页
  40. //向Repeater控件上绑定分页数据源控件
  41. this.Repeater1.DataSource = pds;
  42. this.Repeater1.DataBind();
  43. //使用Literal标签来动态指定每个标签跳转页的链接
  44. ltlPageBar.Text = this.GetPageBar(pds);
  45. }
  46. }
  47. /// <summary>
  48. /// 获取每个标签上的跳转页的链接地址
  49. /// </summary>
  50. /// <param name="pds">分页数据源对象</param>
  51. /// <returns>分页操作按钮的html文本</returns>
  52. private string GetPageBar(PagedDataSource pds)
  53. {
  54. string pageBar = string.Empty; //声明页面标签文本
  55. int currentPageIndex = pds.CurrentPageIndex + 1; //获取当前页索引
  56. //判断首页的链接页面
  57. if (currentPageIndex == 1) //如果该页为第一页,则证明它为首页
  58. {
  59. pageBar += "<a href=\"javascript:void(0)\">首页</a>";
  60. }
  61. else
  62. {
  63. //如果不是首页,首页链接的地址将会为1
  64. pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=1\">首页</a>";
  65. }
  66. //判断上一页链接的地址
  67. if ((currentPageIndex - 1) < 1) //如果上一页小于1则链接到第一页
  68. {
  69. pageBar += "<a href=\"javascript:void(0)\">上一页</a>";
  70. }
  71. else
  72. {
  73. //如果上一页地址不是1将会链接到上一页
  74. pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex - 1) + "\">上一页</a>";
  75. }
  76. //指定下一页的链接地址
  77. if ((currentPageIndex + 1) > pds.PageCount)
  78. {
  79. //如果下一页的地址大于总页数,将会连接到首页
  80. pageBar += "<a href=\"javascript:void(0)\">下一页</a>";
  81. }
  82. else
  83. {
  84. //否则的话链接到下一页
  85. pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex + 1) + "\">下一页</a>";
  86. }
  87. //指定末页的链接地址
  88. if (currentPageIndex == pds.PageCount)
  89. {
  90. pageBar += "<a href=\"javascript:void(0)\">末页</a>";
  91. }
  92. else
  93. {
  94. pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + pds.PageCount + "\">末页</a>";
  95. }
  96. return pageBar; //返回html文本
  97. }
  98. /// <summary>
  99. /// 获取数据源,重新链接数据
  100. /// </summary>
  101. /// <returns>DataTable,数据源</returns>
  102. private DataTable GetDataTable()
  103. {
  104. DataTable dt = new DataTable(); //创建数据库表
  105. using (SqlConnection con = new SqlConnection("server=.;DataBase=MyBlog;uid=sa;pwd=1;"))
  106. {
  107. con.Open(); //打开数据库链接
  108. SqlCommand sqlCom = new SqlCommand(); //声明并创建数据库命令集
  109. StringBuilder sqlStr = new StringBuilder(); //声明sql语句
  110. sqlStr.Append("select * from match"); //获取sql语句
  111. sqlCom.CommandText = sqlStr.ToString(); //为sqlcommand对象指定sql语句
  112. sqlCom.Connection = con; //为sqlcommand对象指定链接对象
  113. SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom); //声明数据库适配器
  114. SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlDa);
  115. sqlDa.Fill(dt); //填充表
  116. }
  117. return dt;
  118. }
  119. }
  120. }

上文Demo下载地址:Repeater使用技巧。
http://files.cnblogs.com/files/netserver/Repeater.zip
下载地址二

结语

文章主要介绍了Repeater控件的基本使用方法,并通过两个示例来更深一步的学习了Repeater控件的使用。虽然Repeater控件封装的操作较少,但它是最基础的数据绑定控件,另外可以通过使用其它控件来弥补Repeater控件的不足,如可以通过使用PagedataSource类来实现数据的分页。文章写到这里并没有结束,下篇文章将会着重讨论ListView

发表评论

表情:
评论列表 (有 0 条评论,573人围观)

还没有评论,来说两句吧...

相关阅读

    相关 数据Repeater

    要不是工作所迫,谁愿意用已没落的技术。 引言 前几篇的文章在说`AJAX`的内容,利用`AJAX`技术能够开发出高效运行的网站应用程序,不过在进行`B/S`项目开发