ASP.NET 數據綁定詳解 代碼+步驟

1. 數據綁定概述

數據綁定指的是從數據源獲取數據,或者向數據源寫入數據。主要有兩種形式:簡單數據綁定數據控件綁定

其中簡單數據綁定分爲屬性綁定、表達式綁定、集合綁定和方法綁定;數據控件綁定分爲ListControl 控件、GridView 控件、DataList 控件和ListView控件

2. 簡單數據綁定

2.1. 屬性綁定

基於屬性的數據綁定所涉及的屬性必須要包含Get訪問器,它的基本語法爲:

<%# 屬性名稱 %>

如果在ASP頁面中對屬性進行了綁定,那麼需要調用Page類的DataBind方法才能執行綁定操作,例如下例:

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- 數據綁定 -->
            <asp:Label ID="Label1" runat="server" Text="圖書名稱:"><%# BookName %></asp:Label>
        </div>
        <div>
        	<!-- 數據綁定 -->
            <asp:Label ID="Label2" runat="server" Text="圖書價格:"><%# BookPrice %></asp:Label>
        </div>
    </form>
</body>

// .aspx.cs文件
// BookName屬性
public string BookName {
    get {
        return "ASP.NET程序設計";
    }
}

// BookPrice屬性
public string BookPrice {
    get {
        return "49";
    }
}

protected void Page_Load(object sender, EventArgs e){
    // 調用DataBind()方法執行綁定
    Page.DataBind();
}

執行結果如下:
在這裏插入圖片描述

2.2. 表達式綁定

表達式綁定的語法與屬性綁定一致,它可以在屬性綁定的基礎上通過表達式對數據進行處理,它的語法如下:

<%# 表達式 %>

例如在屬性綁定的基礎上,要查詢10本書的總價格,則代碼如下:

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- 數據綁定 -->
            <asp:Label ID="Label1" runat="server" Text="圖書名稱:"><%# BookName %></asp:Label>
        </div>
        <div>
        	<!-- 表達式綁定 -->
            <asp:Label ID="Label2" runat="server" Text="圖書價格:"><%# Convert.ToInt32(BookPrice)*10 %></asp:Label>
        </div>
    </form>
</body>

// .aspx.cs文件
// BookName屬性
public string BookName {
    get {
        return "ASP.NET程序設計";
    }
}

// BookPrice屬性
public string BookPrice {
    get {
        return "49";
    }
}

protected void Page_Load(object sender, EventArgs e){
    // 調用DataBind()方法執行綁定
    Page.DataBind();
}

執行結果如下所示
在這裏插入圖片描述

2.3. 集合綁定

有一些服務器控件是多記錄控件,如DropDownList控件, 這類控件即可使用集合作爲數據源對其進行綁定。通常情況下,集合數據源主要包括ArrayList、Hashtabel、 DataView、 DataReader 等。

例如下面代碼,實現了對DropDownList控件進行數據綁定:

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="圖書名稱:"></asp:Label>
            <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
        </div>
    </form>
</body>

protected void Page_Load(object sender, EventArgs e){
    // 構建數據源
    ArrayList arrayList = new ArrayList();
    arrayList.Add("iisexpress");
    arrayList.Add("assembly");
    arrayList.Add("Windows");

	// 指定數據源
    DropDownList1.DataSource = arrayList;
    // 數據綁定
    DropDownList1.DataBind();
}

執行結果如下:
在這裏插入圖片描述

2.4. 方法綁定

方法的綁定與屬性綁定的語法是一致的,只不過把綁定對象更替爲了方法,例如下面的代碼:

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- 數據綁定 -->
            <asp:Label ID="Label1" runat="server" Text="圖書名稱:"><%# BookName %></asp:Label>
        </div>
        <div>
        	<!-- 方法綁定 -->
            <asp:Label ID="Label2" runat="server" Text="圖書價格:"><%# PriceTest("49") %></asp:Label>
        </div>
    </form>
</body>

// .aspx.cs文件
public string PriceTest(string _price) {
    return _price;
}

protected void Page_Load(object sender, EventArgs e){
    // 調用DataBind()方法執行綁定
    Page.DataBind();
}

執行結果如下:
在這裏插入圖片描述

3. 數據控件綁定

3.1. ListControl 控件

ListControl控件用來定義所有列表類型控件的所有屬性方法和事件,是一個抽象基類,它能夠控制的控件主要包括:DropDownList控件、ListBox控件、CheckBoxList控件、RadioButtonList控件。

ListControl控件能夠指定能夠用來填充列表控件的數據源,其中與數據綁定修改的屬性有:

  1. DataSource屬性,用來設置數據源
  2. DataTextField屬性,用來指定提供文本內容的數據源字段
  3. DataValueField屬性,用來指定提供值的數據源字段

例如下面代碼,將圖書列表以DropDownList控件進行顯示,當用戶選擇了DropDownList控件中的某個值後,頁面會進行相應的信息更新。

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- ListControl控件綁定DropDownList -->
            <asp:Label ID="Label1" runat="server" Text="圖書列表:"><%# BookName %></asp:Label>
            <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
        </div>
        <div>
            <asp:Label ID="Label2" runat="server" Text="圖書編碼:"></asp:Label>
            <asp:Label ID="Label3" runat="server" Text=""></asp:Label>
        </div>
        <div>
            <asp:Label ID="Label4" runat="server" Text="圖書名稱:"></asp:Label>
            <asp:Label ID="Label5" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>

// .aspx.cs文件
protected void Page_Load(object sender, EventArgs e){
    if (!IsPostBack) {
        SqlConnection sqlConnection = new SqlConnection("Server=DEITIVOD;Database=db_LibraryMS;User Id=sa;pwd=admin");
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select book_code, book_name from tb_bookinfo;", sqlConnection);

        // 將查詢到的數據放入一個DataSet
        DataSet dataSet = new DataSet();
        sqlDataAdapter.Fill(dataSet);

        // 對DropDownList執行指定數據源和數據綁定
        DropDownList1.DataSource = dataSet;
        DropDownList1.DataTextField = "book_name"; // 指定要顯示的字段
        DropDownList1.DataValueField = "book_code"; // 指定要綁定的主鍵值
        DropDownList1.DataBind();
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
    Label3.Text = DropDownList1.SelectedValue;
    Label5.Text = DropDownList1.SelectedItem.Text;
}

執行效果如下:
數據庫中的tb_bookinfo數據表的數據如下所示:
在這裏插入圖片描述

ASP頁面中顯示的數據:
在這裏插入圖片描述

3.2. GridView 控件

GridView控件可稱之爲數據表格控件,它以表格的形式顯示數據源中的數據,每列表示一個字段,而每行表示一條 記錄,可以將其理解爲數據庫技術中的視圖。

3.2.2. 使用GridView控件綁定數據源

使用GridView控件綁定數據源主要用到

  1. DataSource屬性,用來指定數據源
  2. DataBind方法,用來執行數據綁定

如下代碼實現了將SQL Server數據庫中的數據通過GridView控件顯示到ASP頁面中

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- GridView控件綁定數據源 -->
            <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </div>
    </form>
</body>

// .aspx.cs文件
 protected void Page_Load(object sender, EventArgs e){
    SqlConnection sqlConnection = new SqlConnection("Server=DEITIVOD;Database=db_LibraryMS;User Id=sa;pwd=admin");
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select * from leaveword;", sqlConnection);

    DataSet dataSet = new DataSet();
    sqlDataAdapter.Fill(dataSet);

    GridView1.DataSource = dataSet; // 指定數據集
    GridView1.DataBind(); // 執行數據綁定
}

數據庫中leaveword數據表的數據如下所示:
在這裏插入圖片描述

執行效果如下,ASP頁面中顯示的數據:
在這裏插入圖片描述

3.2.3. 自定義GridView控件的列字段名

GridView中的數據列分爲7種類型

數據列 說明
BoundFiled 最常用的數據列,用來顯示文本
CheckBoxFiled 用來顯示Boolean值
CommandFiled 用來顯示執行選擇、編輯和刪除操作的命令按鈕
ImageFiled 用來顯示圖片
HyperLinkFiled 用來將數據以超鏈接的形式顯示出來
ButtonFiled 用來爲GridView控件創建命令按鈕,該按鈕可以操作其所在行的數據
TemplateFiled 用來給用戶提供自定義類型的數據列

在VS開發環境中按下面的步驟操作,以BoundFiled 爲例將GridView中的字段名修改爲中文顯示:
在這裏插入圖片描述
如果只想顯示我們自定義的列,可以將AutoGenerateColumns設置爲False
在這裏插入圖片描述上面兩張圖的內容也可以通過下面的代碼實現:

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- GridView控件綁定數據源,並且自定義列 -->
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="title" HeaderText="圖書編號" />
                    <asp:BoundField DataField="email" HeaderText="郵箱" />
                    <asp:BoundField DataField="context" HeaderText="內容" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>

// .aspx.cs文件
protected void Page_Load(object sender, EventArgs e){
    SqlConnection sqlConnection = new SqlConnection("Server=DEITIVOD;Database=db_LibraryMS;User Id=sa;pwd=admin");
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select * from leaveword;", sqlConnection);

    DataSet dataSet = new DataSet();
    sqlDataAdapter.Fill(dataSet);

    GridView1.DataSource = dataSet; // 指定數據集
    GridView1.DataBind(); // 執行數據綁定
}

效果如下,左邊是直接指定數據源時的表格,右邊是對列自定義的表格:
在這裏插入圖片描述

3.2.4. 使用GridView控件分頁顯示數據

使用GridView控件分頁顯示數據主要用到了以下兩個屬性和一個事件:

  1. AllowPaging屬性,用來決定是否啓用分頁功能
  2. PageSize屬性,設置分頁時每頁顯示幾條記錄,默認是12條
  3. PageIndexChanging事件,用來響應用戶的頁面切換指令

下圖的GridView屬性說明了該GridView開啓了分頁功能,每頁是展示3條記錄
在這裏插入圖片描述下面的代碼,在開啓分頁功能的基礎上重寫了PageIndexChanging事件,實現了GridView的分頁功能:

// .aspx文件
<body>
    <form id="form1" runat="server">
        <div>
        	<!-- GridView控件綁定數據源,並且使用分頁功能 -->
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="3">
            </asp:GridView>
        </div>
    </form>
</body>

// .aspx.cs文件
protected void Page_Load(object sender, EventArgs e){
	    SqlConnection sqlConnection = new SqlConnection("Server=DEITIVOD;Database=db_LibraryMS;User Id=sa;pwd=admin");
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select * from leaveword;", sqlConnection);

    DataSet dataSet = new DataSet();
    sqlDataAdapter.Fill(dataSet);

    GridView1.DataSource = dataSet; // 指定數據集
    GridView1.DataBind(); // 執行數據綁定
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e){
    // 設置當前頁爲新頁
    GridView1.PageIndex = e.NewPageIndex;
    // 綁定新頁數據
    GridView1.DataBind();
}

執行結果如下:
在這裏插入圖片描述

3.2.5. 選中、編輯和刪除GridView數據項

在ASP.NET中實現選中、編輯和刪除GridView數據項

在這裏插入圖片描述

3.3. DataList 控件

3.3.1. DataList 模板

DataList控件是一個常用的數據綁定控件,可以稱之爲迭代控件,該控件能夠以某種設定好的模板格式循環顯示多條數據,這種模板格式是可以根據需要進行自定義的,比較於GridView控件,雖然GridView控件功能非常強大,但它始終只能以表格的形式顯示數據,而使用DataList控件則靈活性非常強,其本身就是一個富有彈性的控件。

DataList中一共有以下幾種模板:

模板 說明
ItemTemplate 爲項提供內容
AlternatingltemTemplate 爲交替項提供內容,是ItemTemplate的擴展
SelectedltemTemplate 爲當前選定項提供內容
EditltemTemplate 爲當前編輯項提供內容
HeaderTemplate 爲頁眉提供內容
FooterTemplate 爲頁腳提供內容
3.3.2. 分頁顯示DataList控件中的數據

DataList本身不具有分頁功能,爲了實現分頁功能,需要藉助PagedDataSource類,例如這個例子

在這裏插入圖片描述

3.4. ListView控件

3.4.1. ListView控件概述

ListView控件用於顯示數據,它提供了編輯、刪除、插入、分頁與排序等功能,ListView大部分的屬性方法和事件與GridView和DataList一致,可以理解爲GridView控件與DataList控件的融合,它具有GridView控件編輯數據的功能,同時又具有DataList控件靈活佈局的功能。

3.4.2. ListView控件的模板

ListView控件有非常多的模板,其中最常用的有六個

模板 說明
ItemTemplate 爲項提供內容
GroupTemplate 爲組提供內容,它包含一個佔位符對象,可以由其他模板中的內容進行替換
SelectedltemTemplate 爲當前選定項提供內容
EditltemTemplate 爲當前編輯項提供內容
InsertltemTemplate 爲插入項提供內容
EmptyDataTemplate 在數據源未返回數據時提供內容
3.4.3. 使用ListView控件對數據進行顯示、分頁和排序

使用ListView控件對數據進行分頁需要用到標籤,這是一個用於分頁的控件。排序需要用到CommandName屬性,令其值爲sort,指定要進行排序操作,然後再指定CommandArgument屬性,令其值爲要排序的列。

使用ListView控件顯示數據只需配置數據源即可,而無需寫任何一行操作數據庫的代碼,效果如下:
實現步驟
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章