ASP.NET數據綁定


  數據綁定是ASP.NET提供的另一種訪問數據庫的方法。與ADO.NET數據庫訪問技術不同的是:數據綁定技術可以讓程序員不關注數據庫連接、數據庫命令以及如何格式化這些數據以顯示在頁面上等環節,而是直接把數據綁定到HTML元素和Web控件。

  數據控件則是用來顯示從數據庫中獲取的數據。

  數據綁定的原理:

    首先要設置控件的數據源和數據的顯示格式,設置完成后,控件就會自動處理剩余的工作以把要顯示的數據按照要顯示的格式顯示在頁面上。

數據綁定的類型 

  1. 單值綁定。

       可以通過單值綁定的方式把數據添加到ASP.NET頁面的任何地方。可以把數據放在一個控件的屬性定義標記里,也可以直接以純文本的形式放置在HTML標記里。

  2. 多值綁定。

       多值綁定可以顯示一個表中的所有內容。同單值綁定不一樣,這種類型的數據綁定需要支持它的特殊控件。

數據綁定的工作方式

  單值數據綁定和多值數據綁定的工作方式不太一樣。使用單值數據綁定時,需要把數據綁定表達式插入到.aspx文件的標記中。使用多值數據綁定時,必須設置一個數據控件的單個或多個屬性。

  一旦指定了數據綁定,就需要激活它,可以通過調用控件或頁面對象的DataBind方法來激活數據綁定。

  在頁面的Load事件中調用DataBind方法。如果沒有在Load事件中調用DataBind方法的話,ASP.NET將忽略數據綁定表達式,在頁面上將以空值的形式呈現。 

單值綁定

  單值綁定其實就是實現動態文本的一種的方式,為了實現單值數據綁定,可以向ASP.NET頁面文件中添加特殊的數據綁定表達式。

  單值綁定主要有四種數據綁定表達式:

    1.<%=XXX %>,它是內聯引用方式,可以引用C#代碼。

    2.<%# XXX %>,它可以引用.cs文件中的代碼的字段,但這個字段必須初始化后,在頁面的Load事件中使用Page.DataBind方法來實現。

    3.<%#$ XXX %>,它可以引用Web.config文件中預定義的字段或者已注冊的類。

    4.<%# Eval(XXX) %>,它類似於JavaScript,數據源也需要綁定。

  單值綁定的使用:

    在Default.aspx中加入如下代碼:

 1 <div>
 2         <div>
 3             <%# projectName %>
 4             <br />
 5             <br />
 6             <%= DateTime.Now %>
 7         </div>
 8         <br />
 9         <div>
10         </div>
11         <asp:TextBox ID="bindTest" runat="server" Text="<%$ AppSettings:test %>" />
12         <br />
13         <br />
14         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
15             <Columns>
16                 <asp:TemplateField>
17                     <HeaderTemplate>
18                         <asp:Label runat="server" Text="姓名:" />
19                     </HeaderTemplate>
20                     <ItemTemplate>
21                         <%#Eval("Name") %>
22                         <br />
23                     </ItemTemplate>
24                 </asp:TemplateField>
25                 <asp:TemplateField>
26                     <HeaderTemplate>
27                         <asp:Label runat="server" Text="性別:"></asp:Label>
28                     </HeaderTemplate>
29                     <ItemTemplate>
30                         <%#Eval("Sex") %>
31                     </ItemTemplate>
32                 </asp:TemplateField>
33                 <asp:TemplateField>
34                     <HeaderTemplate>
35                         <asp:Label runat="server" Text="年齡:"></asp:Label>
36                     </HeaderTemplate>
37                     <ItemTemplate>
38                         <%#Eval("Age") %>
39                     </ItemTemplate>
40                 </asp:TemplateField>
41             </Columns>
42         </asp:GridView>
43 </div>
View Code

    

    修改Default.aspx.cs中的代碼,代碼如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.UI;
 7 using System.Web.UI.WebControls;
 8 
 9 namespace WebApplication1
10 {
11     public partial class Default : System.Web.UI.Page
12     {
13         public string projectName;
14         protected void Page_Load(object sender, EventArgs e)
15         {
16             ini_table();
17             projectName = "單值綁定";
18             Page.DataBind();
19         }
20         void ini_table()
21         {
22             DataTable dataTable = new DataTable();
23             //用於顯示的Name列
24             dataTable.Columns.Add("Name");
25             dataTable.Columns.Add("Sex");
26             dataTable.Columns.Add("Age");
27             DataRow dataRow = dataTable.NewRow();
28             dataRow[0] = "周周";
29             dataRow[1] = "";
30             dataRow[2] = 23;
31             dataTable.Rows.Add(dataRow);
32 
33             dataRow = dataTable.NewRow();
34             dataRow[0] = "芳芳";
35             dataRow[1] = "";
36             dataRow[2] = 22;
37             dataTable.Rows.Add(dataRow);
38             //數據源綁定
39             this.GridView1.DataSource = dataTable.DefaultView;
40             this.GridView1.DataBind();
41         }
42     }
43 }
View Code

  單值數據綁定的使用非常簡單,且比較靈活,可以隨意的在頁面添加數據綁定,也可以對控件進行數據綁定,但是在使用過程中需要考慮以下單值數據綁定的缺點:

    1.數據綁定的代碼和定義用戶界面的代碼混合在一起。ASP.NET的一個優勢就是把定義用戶界面的代碼同數據訪問代碼和其他操作任務的代碼分開,但是單值數據綁定卻把數據綁定的代碼同定義用戶界面的代碼混合在一起,這樣不方便頁面和代碼的管理,容易引起混亂。

    2.代碼過於分散,使得不同的程序員很難在同一個項目上協同工作。

  單值數據綁定的替代方法:

    為了避免代碼與HTML混用,也為了方便代碼的管理,可以在后台代碼中以賦值的方式替代單值數據綁定,在頁面的Load事件中對控件進行賦值。

多值綁定

  多值綁定使程序員不用編寫循環語句就能把ArrayDataTable中的數據添加到控件中。簡化了支持復雜格式和模板選擇的數據顯示,使得數據能夠自動被配置為控件中要顯示的格式。

  創建多值綁定,需要使用支持數據綁定的控件,ASP.NET提供一系列這類控件:

    1. 列表控件,諸如ListBoxDropDownListCheckBoxListRadioButtonList等。

    2. HtmlSelect,它是一個HTML控件,類似於ListBox控件。

    3. GirdViewDetailsViewFormViewListView等復雜的數據控件。

  多值綁定的使用:

    在Default.aspx中添加以下代碼:

 1     <div>
 2         <table>
 3             <tr>
 4                 <td align="Top" colspan="2">
 5                     <asp:Label ID="Label1" runat="server" Text="新上架的水果:" />
 6                 </td>
 7             </tr>
 8             <tr>
 9                 <td>
10                     <asp:ListBox ID="ListBox1" runat="server" />
11                 </td>
12             </tr>
13         </table>
14     </div>
View Code

    在Default.aspx中的Load事件中添加以下代碼:

1             ArrayList arrayList = new ArrayList();
2             arrayList.Add("香蕉");
3             arrayList.Add("蘋果");
4             arrayList.Add("橘子");
5             this.ListBox1.DataSource = arrayList;
6             this.ListBox1.DataBind();
View Code

強類型集合

  在.NET框架中的命名空間System.Collections.Generic中,存在與哈希表和ArrayList不同的集合,這些集合只能存儲單一類型的對象,這些集合被稱為泛型集合。

  使用泛型集合可以創建強類型集合。

  創建泛型集合時,需要指定存儲項的類型,這樣就確定了集合要存儲的對象的類型。當在集合中添加不同類型的對象時,就會產生編譯錯誤。

  使用泛型集合存儲數據時,不用擔心存入不安全的數據類型,且在訪問的時候也不需要再進行數據轉換,可以提高數據訪問的速度。

  使用泛型集合必須在代碼文件中引用命名空間:Using System.Collections.Generic。

  強類型集合的使用:

    在Default.aspx中添加以下代碼:

 1     <div>
 2         <table>
 3             <tr>
 4                 <td align="Top" colspan="2">
 5                     <asp:Label ID="Label1" runat="server" Text="新上架的水果:" />
 6                 </td>
 7             </tr>
 8             <tr>
 9                 <td>
10                     <asp:ListBox ID="ListBox1" runat="server" />
11                 </td>
12             </tr>
13         </table>
14     </div>
View Code

    在Default.aspx中的Load事件中添加以下代碼:

1             List<string> list = new List<string>();
2             list.Add("香蕉");
3             list.Add("蘋果");
4             list.Add("橘子");
5             this.ListBox1.DataSource = list;
6             this.ListBox1.DataBind();
View Code

字典集合

  Dictionary類位於System.Collections.Generic命名空間下。Dictionary類表示鍵和值的集合,它提供了從一組鍵到一組值的映射。字典中的每個添加項都由一個值及其相關聯的鍵組成。通過鍵來檢索值的速度是非常快的,因為Dictionary類是作為一個哈希表來實現的。在使用HashTable來存儲將要寫入到數據庫或者返回的信息時,在這之間要不斷地進行類型的轉換,增加了系統裝箱和拆箱的負擔,如果操作的數據類型相對確定的話,而用Dictionary<TKey,TValue>集合類來存儲數據就方便多了。

  字典集合的使用:

    在Default.aspx中添加以下代碼:

 1     <div>
 2         <table>
 3             <tr>
 4                 <td align="Top" colspan="2">
 5                     <asp:Label ID="Label1" runat="server" Text="新上架的水果:" />
 6                 </td>
 7             </tr>
 8             <tr>
 9                 <td>
10                     <asp:ListBox ID="ListBox1" runat="server" />
11                 </td>
12             </tr>
13         </table>
14     </div>
View Code

    在Default.aspx中的Load事件中添加以下代碼:

1             Dictionary<int, string> fruit = new Dictionary<int, string>();
2             fruit.Add(1, "香蕉");
3             fruit.Add(2, "蘋果");
4             fruit.Add(3, "橘子");
5             this.ListBox1.DataSource = fruit;
6             this.ListBox1.DataTextField = "Value";
7             this.DataBind();
View Code

數據源控件

  數據源控件用於連接數據源、從數據源中讀取數據以及把數據寫入數據源。數據源控件不呈現任何用戶界面,而是充當特定數據源(如數據庫、業務對象或XML文件)與ASP.NET網頁上的其他控件之間的橋梁。數據源控件實現了豐富的數據檢索和修改功能,其中包括查詢、排序、分頁、篩選、更新、刪除以及插入。

  使用數據源控件可以不用編寫任何代碼就可以實現頁面的數據綁定。.NET Framework包含支持不同數據綁定方案的數據源控件,這些控件可以使用不同的數據源。此外,數據源控件模型是可擴展的,因此用戶還可以創建自己的數據源控件,實現與不同數據源的交互,或為現有的數據源提供附加功能。

  .NET框架提供了七個數據源控件,如下:

    1.ObjectDataSource控件:表示具有數據檢索和更新功能的中間層對象,允許使用業務對象或其他類,並可創建依賴中間層對象管理數據庫的Web應用程序。

    2.SqlDataSource控件:用來訪問存儲在關系數據庫中的數據。這些數據庫包括Microsoft SQL Server以及OLE DB和ODBC數據源。它與SQL Server一起使用時支持高級緩存功能。當數據作為DataSet對象返回時,此控件還支持排序、篩選和分頁。

    3.AccessDataSource控件:主要用來訪問Microsoft Access數據庫。當數據作為DataSet對象返回時,此控件還支持排序、篩選和分頁。

    4.XmlDataSource控件:主要用來訪問XML文件,特別適用於分層的ASP.NET服務器控件,如TreeView控件、Menu控件。它支持使用XPath表達式來實現篩選功能,並允許對數據應用XSLT轉換。它允許通過保存更改后的整個XML文檔來更新數據。

    5.SiteMapDataSource控件:結合ASP.NET站點導航使用。

    6.EntityDataSource控件:支持基於實體數據庫模型(EDM)的數據綁定方案。此數據規范將數據表示為實體和關系集。它支持自動生成更新、插入、刪除、和選擇命令以及排序、篩選和分頁。

    7.LinqDataSource控件:使用LinqDataSource控件,可以在ASP.NET網頁中使用LINQ,從數據表或內存數據集合中檢索數據。使用聲明性標記,可以編寫對數據進行檢索、篩選、排序和分組操作所需的全部條件。從SQL數據庫表中檢索數據時,也可以配置LinqDataSource控件來處理更新、插入和刪除操作。

  SqlDataSource控件

    可以將 SqlDataSource控件和用於顯示數據的其他控件(如GridView、FormView和DetailsView控件)結合使用,使用很少的代碼或不使用代碼就可以在ASP.NET網頁中顯示和操作數據。

    SqlDataSource控件使用ADO.NET類與ADO.NET支持的任何數據庫進行交互。SqlDataSource控件使用ADO.NET類提供的提供器訪問數據庫。 

    使用SqlDataSource控件連接SQL Server數據庫。

      在配置文件中添加:

1 <connectionStrings>
2     <add name="ConnectionString" connectionString="Data Source=追風的蝸牛;Initial Catalog=Adrotator;Integrated Security=True"/>
3 </connectionStrings>
View Code

      在Default.aspx中添加以下代碼:

 1     <div>
 2         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ConnectionStrings:ConnectionString %>"
 3             ProviderName="System.Data.SqlClient" DataSourceMode="DataReader" SelectCommand="select * from Advertisements">
 4         </asp:SqlDataSource>
 5         <table>
 6             <tr>
 7                 <td align="Top" colspan="2">
 8                     <asp:Label ID="Label1" runat="server" Text="廣告:" />
 9                 </td>
10             </tr>
11             <tr>
12                 <td>
13                     <asp:ListBox ID="ListBox1" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="true"
14                          DataTextField="AlternateText" DataValueField="ID" Width="200px" Height="200px">
15                         </asp:ListBox>
16                 </td>
17             </tr>
18         </table>
19     </div>
View Code

    SqlDataSource控件的功能:

      1.執行數據庫操作命令。

        SelectCommand、UpdateCommand、DeleteCommand 和 InsertCommand四個屬性對應數據庫操作的四個命令:選擇、更新、刪除和插入,可以通過設置這四個屬性來執行相應的數據庫操作命令。只需要把對應的SQL語句賦予這四個屬性,SqlDataSource控件即可完成對數據庫的操作。

      2.返回DataSet或DataReader對象。

        SqlDataSource控件可以返回兩種格式的數據:作為DataSet對象或ADO.NET數據讀取器。通過設置數據源控件的DataSourceMode屬性,可以指定要返回的格式。 

      3.進行緩存。

        SqlDataSource控件可以緩存它已檢索的數據,可以避免開銷很大的查詢操作,從而增強應用程序的性能。只要數據相對穩定,且緩存的結果小得足以避免占用過多的系統內存,就可以使用緩存。

        默認情況下不啟用緩存,將EnableCaching屬性設置為true,便可以啟用緩存。

      4.篩選。

        如果已為SqlDataSource控件啟用緩存,並且已將數據集指定為Select查詢返回的數據格式,則還可以篩選數據,不需重新運行該查詢。

        SqlDataSource控件支持FilterExpression屬性,可以使用該屬性指定應用於由數據源控件維護的數據的選擇條件。還可以創建特殊的FilterParameters對象,這些對象在運行時為篩選表達式提供值,從而對篩選表達式進行參數化。

    使用SqlDataSource控件檢索數據:

      使用SqlDataSource控件從數據庫中檢索數據,要設置一下屬性:

        1.ProviderName:設置為ADO.NET提供程序的名稱,該提供程序表示正在使用的數據庫。

        2.ConnectionString:設置為用於數據庫的連接字符串。

        3.SelectCommand:設置為從數據庫中返回數據的SQL查詢或存儲過程。

      使用SqlDataSource控件從數據庫中檢索數據。

        在配置文件中添加:

1   <connectionStrings>
2     <add name="ConnectionString" connectionString="Data Source=追風的蝸牛;Initial Catalog=Adrotator;Integrated Security=True"/>
3   </connectionStrings>
View Code

        在Default.aspx中添加以下代碼:

 1     <div>
 2         請選擇:
 3         <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
 4             <asp:ListItem>冰山</asp:ListItem>
 5             <asp:ListItem>荷塘</asp:ListItem>
 6             <asp:ListItem>落日</asp:ListItem>
 7         </asp:DropDownList>
 8         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ConnectionStrings:ConnectionString %>"
 9             ProviderName="System.Data.SqlClient" DataSourceMode="DataReader" SelectCommand="select * from Advertisements where AlternateText=@text">
10             <SelectParameters>
11                 <asp:ControlParameter Name="text" ControlID="DropDownList1" PropertyName="SelectedValue" />
12             </SelectParameters>
13         </asp:SqlDataSource>
14         <br />
15         <asp:Label Text="導航鏈接:" runat="server" />
16         <br />
17         <asp:ListBox ID="ListBox1" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="true"
18                          DataTextField="NavigateUrl" DataValueField="ID" Width="200px" Height="200px">
19                         </asp:ListBox>
20     </div>
View Code

    使用參數:

      SqlDataSource控件可以使用參數執行下列操作:

        1.提供用於數據檢索的搜索條件;

        2.提供要在數據存儲區中插入、更新或刪除的值;

        3.提供用於排序、分頁和篩選的值。

        4.借助參數,使用少量自定義代碼或不使用自定義代碼就可篩選數據和創建主/從應用程序。

      可以從各種源中獲取參數值。通過Parameter對象,可以從Web服務器控件屬性、Cookie、會話狀態、QueryString字段、用戶配置文件屬性及其他源中提供值給參數化數據操作。

      SqlDataSource控件的參數類型

        1.ControlParameter:將參數設置為ASP.NET網頁中的Control的屬性值。

        2.CookieParameter:將參數設置為HttpCookie對象的值。

        3.FormParameter:將參數設置為HTML窗體字段的值。

        4.ProfileParameter:將參數設置為當前用戶配置文件(Profile) 中的屬性的值。

        5.QueryStringParameter:將參數設置為QueryString字段的值。使用QueryStringField屬性指定QueryString字段的名稱。

        6. SessionParameter:將參數設置為Session對象的值。使用SessionField屬性指定Session對象的名稱。

      使用SqlDataSource控件。該控件使用參數化命令查詢和修改數據綁定控件中的數據。

        在配置文件中添加:

1   <connectionStrings>
2     <add name="ConnectionString" connectionString="Data Source=追風的蝸牛;Initial Catalog=Adrotator;Integrated Security=True"/>
3   </connectionStrings>
View Code

        在Default.aspx中添加以下代碼:

 1     <div>
 2         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ConnectionStrings:ConnectionString %>"
 3             ProviderName="System.Data.SqlClient" DataSourceMode="DataReader" SelectCommand="select AlternateText,ID from Advertisements">
 4         </asp:SqlDataSource>
 5         <br />
 6         <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ConnectionStrings:ConnectionString %>" 
 7             ProviderName="System.Data.SqlClient" DataSourceMode="DataReader" 
 8             SelectCommand="select * from Advertisements where ID=@ID" 
 9             InsertCommand="insert into Advertisements(ID,ImageUrl,NavigateUrl,Impressions,AlternateText) 
10             values(@ID,@ImageUrl,@NavigateUrl,@Impressions,@AlternateText); select @ID=scope_Identity()" 
11             UpdateCommand="update Advertisements set ImageUrl=@ImageUrl,NavigateUrl=@NavigateUrl,Impressions=@Impressions,AlternateText=@AlternateText where ID=@ID" 
12             DeleteCommand="delete Advertisements where ID=@ID" OnInserted="SqlDataSource2_Inserted">
13             <SelectParameters>
14                 <asp:ControlParameter Name="ID" ControlID="DropDownList1" PropertyName="SelectedValue" Type="String" DefaultValue="1" />
15             </SelectParameters>
16             <InsertParameters>
17                 <asp:Parameter Name="ImageUrl" Type="String" />
18                 <asp:Parameter Name="NavigateUrl" Type="String" />
19                 <asp:Parameter Name="Impressions" Type="String" />
20                 <asp:Parameter Name="AlternateText" Type="String" />
21                 <asp:Parameter Name="ID" Type="String" DefaultValue="1" />
22             </InsertParameters>
23             <UpdateParameters>
24                 <asp:Parameter Name="ImageUrl" Type="String" />
25                 <asp:Parameter Name="NavigateUrl" Type="String" />
26                 <asp:Parameter Name="Impressions" Type="String" />
27                 <asp:Parameter Name="AlternateText" Type="String" />
28                 <asp:Parameter Name="ID" Type="String" DefaultValue="1" />
29             </UpdateParameters>
30             <DeleteParameters>
31                 <asp:Parameter Name="ID" Type="String" DefaultValue="1" />
32             </DeleteParameters>
33         </asp:SqlDataSource>
34         <br />
35         <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" DataSourceID="SqlDataSource1" 
36             DataTextField="AlternateText" DataValueField="ID" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
37         </asp:DropDownList>
38         <br />
39         <asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="SqlDataSource2" AutoGenerateRows ="false" 
40             AutoGenerateInsertButton="true" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" DataKeyNames="ID" 
41             GridLines="Both" OnItemDeleted="DetailsView1_ItemDeleted" OnItemUpdated="DetailsView1_ItemUpdated">
42             <HeaderStyle BackColor="Wheat" ForeColor="PaleGoldenrod" />
43             <RowStyle BackColor="White" />
44             <AlternatingRowStyle BackColor="Lavender" />
45             <EditRowStyle BackColor="LavenderBlush" />
46             <Fields>
47                 <asp:BoundField DataField="ID" HeaderText="廣告編號" InsertVisible="false" ReadOnly="true" />
48                 <asp:BoundField DataField="ImageUrl" HeaderText="圖片地址" />
49                 <asp:BoundField DataField="NavigateUrl" HeaderText="鏈接地址" />
50                 <asp:BoundField DataField="Impressions" HeaderText="顯示頻率" />
51                 <asp:BoundField DataField="AlternateText" HeaderText="廣告名稱" />
52             </Fields>
53         </asp:DetailsView>
54     </div>
View Code

        Defau.aspx.cs中的代碼如下:

 1 using System;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 using System.Data;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.UI;
 8 using System.Web.UI.WebControls;
 9 
10 namespace WebApplication1
11 {
12     public partial class Default : System.Web.UI.Page
13     {
14         //public string projectName;
15         protected void Page_Load(object sender, EventArgs e)
16         {
17 
18         }
19 
20         protected void SqlDataSource2_Inserted(object sender, SqlDataSourceStatusEventArgs e)
21         {
22             System.Data.Common.DbCommand command = e.Command;
23             DropDownList1.DataBind();
24             this.DetailsView1.DataBind();
25         }
26 
27         protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
28         {
29             this.DetailsView1.DataBind();
30         }
31 
32         protected void DetailsView1_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
33         {
34             DropDownList1.DataBind();
35         }
36 
37         protected void DetailsView1_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
38         {
39             this.DropDownList1.DataBind();
40             DropDownList1.SelectedValue = e.Keys["ID"].ToString();
41             DetailsView1.DataBind();
42         }
43     }
44 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM