1. 程式人生 > >【Asp.net之旅】--資料繫結控制元件之Repeater

【Asp.net之旅】--資料繫結控制元件之Repeater

引言


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

<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>內容</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負責接收前臺傳進來的按鈕命令,根據命令的引數來設定後臺傳遞的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>
        /// 窗體載入時繫結資料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.DataBindToRepeater();//將資料繫結到Repeater控制元件上
            }
        }

        /// <summary>
        /// 將資料來源繫結Repeater控制元件上
        /// </summary>
        private void DataBindToRepeater() {
            //使用using語句進行資料庫連線
            using (SqlConnection sqlCon=new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
            {
                sqlCon.Open();  //開啟資料庫連線

                SqlCommand sqlcom = new SqlCommand();   //建立資料庫命令物件
                sqlcom.CommandText = "select * from match"; //為命令物件指定執行語句
                sqlcom.Connection = sqlCon; //為命令物件指定連線物件

                this.userRepeat.DataSource = sqlcom.ExecuteReader();    //為Repeater物件指定資料來源
                this.userRepeat.DataBind(); //繫結資料來源
            }
        }

        /// <summary>
        /// Repeater控制元件命令事件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void userRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            //獲取命令文字,判斷髮出的命令為何種型別,根據命令型別呼叫事件
            if (e.CommandName=="Edit")  //編輯命令
            {
                id = int.Parse(e.CommandArgument.ToString());   //獲取命令ID號
            }
            else if (e.CommandName=="Cancel")   //取消更新命令
            {
                id = -1;
            }
            else if(e.CommandName=="Delete")    //刪除行內容命令
            {
                id = int.Parse(e.CommandArgument.ToString());   //獲取刪除行的ID號
                //刪除選定的行,並重新指定繫結操作
                this.DeleteRepeater(id);
            }
            else if (e.CommandName == "Update") //更新行內容命令
            {
                //獲取更新行的內容和ID號
                string strText = ((TextBox)e.Item.FindControl("txtName")).Text.Trim();
                int intId=int.Parse(((Label)e.Item.FindControl("lblID")).Text);
                //更新Repeater控制元件的內容
                this.UpdateRepeater(strText,intId);
            }

            //重新繫結控制元件上的內容
            this.DataBindToRepeater();
        }

        /// <summary>
        /// 刪除行內容
        /// </summary>
        /// <param name="intId">刪除行所在內容的ID</param>
        private void DeleteRepeater(int intId) {
            using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
            {
                sqlCon.Open();  //開啟資料庫連線

                SqlCommand sqlcom = new SqlCommand();   //建立資料庫命令物件
                sqlcom.CommandText = "delete from match where [email protected]"; //為命令物件指定執行語句
                sqlcom.Connection = sqlCon; //為命令物件指定連線物件

                //建立引數集合,並向sqlcom中新增引數集合
                SqlParameter sqlParam = new SqlParameter("@id", intId);
                sqlcom.Parameters.Add(sqlParam);

                sqlcom.ExecuteNonQuery();   //指定更新語句

            }
        }

        /// <summary>
        /// 更新Repeater控制元件中的內容
        /// </summary>
        /// <param name="strText">修改後的內容</param>
        /// <param name="intId">內容所在行的ID號</param>
        private void UpdateRepeater(string strText,int intId) {
            using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
            {
                sqlCon.Open();  //開啟資料庫連線

                SqlCommand sqlcom = new SqlCommand();   //建立資料庫命令物件
                sqlcom.CommandText = "update match set [email protected] where [email protected]"; //為命令物件指定執行語句
                sqlcom.Connection = sqlCon; //為命令物件指定連線物件

                //建立引數集合,並向sqlcom中新增引數集合
                SqlParameter[] sqlParam = { new SqlParameter("@str", strText), new SqlParameter("@id", intId) };
                sqlcom.Parameters.AddRange(sqlParam);

                sqlcom.ExecuteNonQuery();   //指定更新語句
                
            }
        }

        /// <summary>
        /// Repeater控制元件資料繫結時發生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void userRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //判斷Repeater控制元件中的資料是否是繫結的資料來源,如果是的話將會驗證是否進行了編輯操作
            //ListItemType 列舉表示在一個列表控制元件可以包括,例如 DataGrid、 DataList和 Repeater 控制元件的不同專案。 
            if (e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
            {
                //獲取繫結的資料來源,這裡要注意上面使用sqlReader的方法來繫結資料來源,所以下面使用的DbDataRecord方法獲取的
                //如果繫結資料來源是DataTable型別的使用下面的語句就會報錯.
                System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord)e.Item.DataItem;
                //DataTable型別的資料來源驗證方式
                //System.Data.DataRowView record = (DataRowView)e.Item.DataItem;

                //判斷資料來源的id是否等於現在的id,如果相等的話證明現點選了編輯觸發了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標籤,用來動態新增並指定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">內容</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控制元件的資料來源是PagedDataSource物件,在頁面載入時為該物件動態指定了分頁的屬性,並使用Literal標籤來動態指定每個標籤跳轉頁的連結

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)
            {
                //設定當前頁的索引
                int pageIndex = 1;
                try
                {
                    //獲取當前索要跳轉頁的索引號
                    pageIndex = Convert.ToInt32(Request.QueryString["Page"]);
                    //如果是第0頁將會跳轉入第1頁
                    if (pageIndex <= 0)
                    {
                        pageIndex = 1;
                    }
                }
                catch
                {
                    pageIndex = 1;
                }

                DataTable dt = this.GetDataTable(); //獲取繫結的資料表

                PagedDataSource pds = new PagedDataSource();    //建立分頁資料來源物件                
                pds.DataSource = dt.DefaultView;    //為資料來源物件設定資料來源
                pds.AllowPaging = true; //物件允許分頁
                pds.PageSize = 2;   //設定物件每頁顯示的大小
                pds.CurrentPageIndex = pageIndex - 1; //設定資料來源的當前頁

                //向Repeater控制元件上繫結分頁資料來源控制元件
                this.Repeater1.DataSource = pds;
                this.Repeater1.DataBind();

                //使用Literal標籤來動態指定每個標籤跳轉頁的連結
                ltlPageBar.Text = this.GetPageBar(pds);
            }
        }

        /// <summary>
        /// 獲取每個標籤上的跳轉頁的連結地址
        /// </summary>
        /// <param name="pds">分頁資料來源物件</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)
            {
                //如果下一頁的地址大於總頁數,將會連線到首頁
                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>
        /// 獲取資料來源,重新連結資料
        /// </summary>
        /// <returns>DataTable,資料來源</returns>
        private DataTable GetDataTable()
        {
            DataTable dt = new DataTable(); //建立資料庫表
            using (SqlConnection con = new SqlConnection("server=.;DataBase=MyBlog;uid=sa;pwd=1;"))
            {

                con.Open(); //開啟資料庫連結

                SqlCommand sqlCom = new SqlCommand();    //宣告並建立資料庫命令集
                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);  //宣告資料庫介面卡
                SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlDa);
                sqlDa.Fill(dt); //填充表
            }

            return dt;
        }

    }
}

       

結語

         文章主要介紹了Repeater控制元件的基本使用方法,並通過兩個示例來更深一步的學習了Repeater控制元件的使用。雖然Repeater控制元件封裝的操作較少,但它是最基礎的資料繫結控制元件,另外可以通過使用其它控制元件來彌補Repeater控制元件的不足,如可以通過使用PagedataSource類來實現資料的分頁。文章寫到這裡並沒有結束,下篇文章將會著重討論ListView。