1. 程式人生 > >數據綁定控件之Repeater

數據綁定控件之Repeater

collect order http star 總結 temp bject ase emc

引言


前幾篇的文章在說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="">
  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>

後臺代碼:在後臺代碼中很重要的兩個事件是ItemCommand和ItemDataBound,其中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 [email protected]"; //為命令對象指定執行語句
  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 [email protected] where [email protected]"; //為命令對象指定執行語句
  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">
  6. .pageBar
  7. {
  8. margin-top: 10px;
  9. }
  10. .pageBar a
  11. {
  12. color: #333;
  13. font-size: 12px;
  14. margin-right: 10px;
  15. padding: 4px;
  16. border: 1px solid #ccc;
  17. text-decoration: none;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <form id="form1" runat="server">
  23. <div>
  24. <asp:Repeater ID="Repeater1" runat="server" >
  25. <HeaderTemplate>
  26. <table border="1" cellpadding="0" cellspacing="0" style="width:1006px;border-collapse:collapse; text-align:center;">
  27. <tr>
  28. <th style="ID</th>
  29. <th style="內容</th>
  30. </tr>
  31. </HeaderTemplate>
  32. <ItemTemplate>
  33. <tr>
  34. <td><asp:Label ID="lblId" runat="server" Text=‘<%# DataBinder.Eval(Container.DataItem,"id") %>‘ ></asp:Label></td>
  35. <td><%# DataBinder.Eval(Container.DataItem,"name") %></td>
  36. </tr>
  37. </ItemTemplate>
  38. <FooterTemplate>
  39. </table>
  40. </FooterTemplate>
  41. </asp:Repeater>
  42. </div>
  43. <div class="pageBar">
  44. <asp:Literal ID="ltlPageBar" runat="server"></asp:Literal>
  45. </div>
  46. </form>
  47. </body>
  48. </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. }

數據綁定控件之Repeater