Help and Support

文章編號: 307860 - 上次校閱: 2007年5月18日 - 版次: 4.8

ASP.NET 資料繫結概觀

本文參照下列 Microsoft .NET Framework 類別庫 (Class Library) 的命名空間:
  • System.Data
  • System.Data.SqlClient

在此頁中

全部展開 | 全部摺疊

結論

本文件將會簡介 ASP.NET 資料繫結。

如需其他 ASP.NET 概觀,請參考下列「Microsoft 知識庫」文件:
305140? (http://support.microsoft.com/kb/305140/ ) INFO:ASP.NET 藍圖

其他相關資訊

運用 ASP.NET 資料繫結,您可以將任何伺服器控制項繫結至簡單的屬性、集合、運算式和 (或) 方法。使用資料繫結,您從資料庫或以其他方式使用資料時可以擁有更多的彈性。

本文將討論下列資料繫結主題:

資料繫結須知

<%# %> 語法

ASP.NET 引進新的宣告語法:<%# %>。這是 .aspx 網頁中使用資料繫結的基本語法。這些字元必須包含所有資料繫結運算式。下列清單包含多重來源的簡單資料繫結範例:
  • 簡單屬性 (客戶的語法):
    <%# custID %>
    					
  • 集合 (訂單的語法):
    <asp:ListBox id="List1" datasource='<%# myArray %>' runat="server">
    					
  • 運算式 (連絡人的語法):
    <%# ( customer.First Name + " " + customer.LastName ) %>
    					
  • 方法結果 (未清餘額的語法):
    <%# GetBalance(custID) %>
    					
上述範例中,<%# %> 標籤會指出特定資料來源資訊在 .aspx 網頁中的位置。下列資料繫結範例會使用 TextBox Web 伺服器控制項:
<asp:textbox id=txt text="<%# custID %>" runat=server />
				
如需有關資料繫結語法的詳細資訊,請參閱下列 .NET Framework Software Development Kit (SDK) 文件:
資料繫結運算式語法 (英文)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us /cpgenref/html/cpcondatabindingexpressionsyntax.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpcondatabindingexpressionsyntax.asp)

Page.DataBind() 及 Control.DataBind()

在為 .aspx 網頁上的物件決定和設定特定資料來源之後,您就必須將資料繫結至這些資料來源。您可以使用 Page.DataBindControl.DataBind 方法來將資料繫結至資料來源。

這兩種方法的運作方式很類似。主要的不同在於,呼叫 Page.DataBind 方法之後,所有的資料來源均繫結至伺服器控制項。在您明確地呼叫 Web 伺服器控制項的 DataBind 方法,或網頁層級的 Page.DataBind 方法之前,資料不會呈現給控制項。一般而言,Page.DataBind (或 DataBind) 是從 Page_Load 事件呼叫的。

如需有關 DataBind 方法的詳細資訊,請參閱下列 .NET Framework SDK 文件:Control.DataBind 方法 (英文)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us /cpref/html/frlrfSystemWebUIControlClassDataBindTopic.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIControlClassDataBindTopic.asp)

資料繫結清單控制項

這種清單控制項是特別的 Web 伺服器控制項,能夠繫結至集合。您可以使用這些控制項,以自訂的範本格式顯示資料列。所有的清單控制項都有公開 DataSourceDataMember 屬性,這些屬性是用來繫結至集合。

這些控制項可以將其 DataSource 屬性繫結至支援 IEnumerableICollectionIListSource 介面的任何集合。

Repeater 控制項

Repeater 控制項是範本化的資料繫結清單。Repeater 控制項沒有外觀,亦即沒有內建配置或樣式。因此,您必須在控制項的範本中,明確宣告所有的 HTML 配置、格式和樣式標籤。

下列程式碼範例示範如何使用一個清單控制項,也就是 Repeater 控制項來顯示資料:

注意:您必須根據自已的環境,視需要修改連線字串的參數。

Visual Basic .NET
<%@ Page Language="vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)

   Dim cnn As SqlConnection = New SqlConnection("server=(local);" & _
                                                "database=pubs;Integrated Security=SSPI")
   Dim cmd As SqlDataAdapter = New SqlDataAdapter("select * from authors", cnn)
   Dim ds As DataSet = New DataSet()
   cmd.Fill(ds)
   Repeater1.DataSource = ds
   Repeater1.DataBind()

End Sub
</script>
<html>
<body>
   <form id="Form1" method="post" runat="server">
      <asp:Repeater id="Repeater1" runat="server">
         <ItemTemplate>
         <%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
	 </ItemTemplate>
      </asp:Repeater>
   </form>
</body>
</html>
				
Visual C# .NET
<%@ Page language="c#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
void Page_Load(Object sender, EventArgs e) 
{ 
   SqlConnection cnn = new 
       SqlConnection("server=(local);database=pubs;Integrated Security=SSPI"); 
   SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn); 
   DataSet ds = new DataSet(); 
   da.Fill(ds, "authors"); 
   Repeater1.DataSource = ds.Tables["authors"];
   Repeater1.DataBind();
}
</script>
<html>
<body>
   <form id="WebForm2" method="post" runat="server">
      <asp:Repeater id="Repeater1" runat="server">
         <ItemTemplate>
         <%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
    	 </ItemTemplate>
      </asp:Repeater>
   </form>
</body>
</html>
				
Visual J# .NET
<%@ Page language="VJ#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

 <script runat="server">
void Page_Load(Object sender, EventArgs e) 
{ 
    SqlConnection cnn = new SqlConnection("server=(local);database=pubs;Integrated
         Security=SSPI"); 
    SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn); 
    DataSet ds = new DataSet(); 
    da.Fill(ds, "authors"); 
    DataTableCollection dtc = ds.get_Tables();
    int index = dtc.IndexOf("authors");
    Repeater1.set_DataSource(dtc.get_Item(index));
    Repeater1.DataBind();
}
</script>
<html>
<body>
   <form id="WebForm2" method="post" runat="server">
      <asp:Repeater id="Repeater1" runat="server">
         <ItemTemplate>
         <%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
             </ItemTemplate>
      </asp:Repeater>
   </form>
</body>
</html>
				
如需有關 Repeater 控制項的詳細資訊,請參閱下列 .NET Framework SDK 文件:
Repeater Web 伺服器控制項 (英文)
http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconrepeaterwebservercontrol.asp (http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconrepeaterwebservercontrol.asp)

DataList 控制項

DataList 類別是具有豐富功能的範本化資料繫結清單。您可以修改範本,以自訂此控制項。不同於 Repeater 控制項,DataList 支援指向顯示,並能選擇在執行階段在 HTML 表格中顯示。

如需有關 DataList 控制項的詳細資訊,請參閱下列 .NET Framework SDK 文件:
DataList Web 伺服器控制項 (英文)
http://msdn.microsoft.com/library/en-us/cpgenref/html/cpcondatalistwebservercontrol.asp (http://msdn.microsoft.com/library/en-us/cpgenref/html/cpcondatalistwebservercontrol.asp)

DataGrid 控制項

DataGrid 控制項是具有完整功能、多欄的資料繫結方格。如果要自訂 DataGrid 中個別資料行的配置,您可以將資料行類型設為 [範本],並且修改資料行範本。DataGrid 控制項可以在沒有範本的情況下加以呈現,有助於報告狀況。DataGrid 也支援選取、編輯、刪除、分頁,以及依欄和按鈕欄來排序。

如需有關 DataGrid 控制項的詳細資訊,請參閱下列 .NET Framework SDK 文件:
DataGrid Web 伺服器控制項 (英文)
http://msdn.microsoft.com/library/en-us/cpgenref/html/cpcondatagridwebservercontrol.asp (http://msdn.microsoft.com/library/en-us/cpgenref/html/cpcondatagridwebservercontrol.asp)

存取資料

本節將說明如何從資料庫存取資料,並將資料繫結至清單控制項。您可以使用 DataSetDataReader 類別,以取得資料庫的資料。

DataSet 類別

一個 DataSet 包含完整的資料表示,包括表格結構、表格之間的關係,以及資料的順序。DataSet 類別能夠靈活地加以運用,以便將任何資料庫資訊儲存至「可延伸標記語言」(XML) 檔案中。DataSet 類別是沒有狀態的,這表示您必須在沒有連至伺服器連線資源的情況下,從用戶端將這些類別傳送至伺服器。下列程式碼示範如何使用 DataSet 將資料繫結至控制項:

注意:您必須根據自已的環境,視需要修改連線字串的參數。

Visual Basic .NET
Dim cnn As SqlConnection = New SqlConnection("server=(local);" & _
                                             "database=pubs;Integrated Security=SSPI")
Dim cmd As SqlDataAdapter = New SqlDataAdapter("select * from authors", cnn)
Dim ds As DataSet = New DataSet()
cmd.Fill(ds)
MyRepeater.DataSource = ds
MyRepeater.DataBind() 
				
Visual C# .NET
SqlConnection cnn = new SqlConnection("server=(local);
                                       database=pubs;Integrated Security=SSPI"); 
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn); 
DataSet ds = new DataSet(); 
da.Fill(ds);
MyRepeater.DataSource = ds;
MyRepeater.DataBind(); 
				
Visual J# .NET
SqlConnection cnn = new SqlConnection("server=(local);
                                       database=pubs;Integrated Security=SSPI"); 
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn); 
DataSet ds = new DataSet(); 
da.Fill(ds); 
MyRepeater.set_DataSource(ds);
MyRepeater.DataBind();
				
如需有關 DataSet 類別的詳細資訊,請參閱下列 .NET Framework SDK 文件:
DataSet 類別 (英文)
http://msdn2.microsoft.com/en-us/library/system.data.dataset(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.data.dataset(vs.71).aspx)

DataReader 類別

相反地,如果只要顯示 (而不變更) 將要顯示的資料,DataReader 類別就可能是更好的解決方案。例如,DropDownList 控制項適合使用 DataReader,因為 DataReader 是只轉送的資料游標。下列程式碼將告訴您,如何使用 SqlDataReader 類別,將資料繫結到控制項:

Visual Basic .NET
 Dim cnn As SqlConnection = New SqlConnection("server=(local);" & _
                                              "database=pubs;Integrated Security=SSPI") 
Dim cmd As SqlCommand = New SqlCommand("select * from authors", cnn)  
cnn.Open() 
MyRepeater.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection) 
MyRepeater.DataBind()
 				
Visual C# .NET
 SqlConnection cnn = new SqlConnection("server=(local);
                                        database=pubs;Integrated Security=SSPI"); 

SqlCommand cmd = new SqlCommand("select * from authors", cnn);  

cnn.Open(); 
MyRepeater.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
MyRepeater.DataBind();
 				
Visual J# .NET
 SqlConnection cnn = new SqlConnection("server=(local);
                                        database=pubs;Integrated Security=SSPI");   

SqlCommand cmd = new SqlCommand("select * from authors", cnn);   

cnn.Open(); 
MyRepeater.set_DataSource(cmd.ExecuteReader(CommandBehavior.CloseConnection)); 
MyRepeater.DataBind();
 				
如需有關 SqlDataReader 類別和以 ASP.NET 存取資料的詳細資訊,請參閱 .NET Framework SDK 文件中的下列主題:
SqlDataReader 類別 (英文)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us /cpref/html/frlrfSystemDataSqlClientSqlDataReaderClassTopic.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataSqlClientSqlDataReaderClassTopic.asp)

開發高效能 ASP.NET 應用程式 (英文)
http://msdn2.microsoft.com/en-us/library/5dws599a(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/5dws599a(vs.71).aspx)

在清單控制項範本中繫結

您可以使用清單控制項中的範本來繫結並自訂資料來源的個別記錄。本節包含了 3 個執行方法。

DataBinder.Eval 方法

當資料來源與資料庫傳回的資料一起運作時,就有可能包含數項資訊。您可以使用一般 DataBinder.Eval 方法,以傳回資料。在下列程式碼範例中,au_id 欄位是容器物件的資料來源所傳回的。
 <%# DataBinder.Eval(Container.DataItem,"au_id") %> 				
如需有關 DataBinder.Eval 方法的詳細資訊,請參閱下列 .NET Framework SDK 文件:
DataBinder.Eval 方法 (英文)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us /cpref/html/frlrfSystemWebUIDataBinderClassEvalTopic.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIDataBinderClassEvalTopic.asp)

明確轉型

如果需要更多控制項,請使用明確轉型。明確轉換會使用型別轉換關鍵字。這些關鍵字可以如函數般執行,但是編譯器會產生內嵌程式碼。因此,執行速度比函數呼叫稍快。下列程式碼範例使用明確轉換:

Visual Basic .NET
' DataTable as the DataSource
<%# CType(Container.DataItem, System.Data.DataRowView)("au_id") %>

' DataReader as the DataSource
<%# CType(Container.DataItem, System.Data.Common.DbDataRecord)("au_id") %>

' DataReader as the DataSource
<%# CType(Container.DataItem, System.Data.Common.DbDataRecord)(0) %>
				
Visual C# .NET
// DataTable as the DataSource
<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %> 

// DataReader as the DataSource
<%# ((System.Data.Common.DbDataRecord)Container.DataItem)["au_id"] %>

// DataReader as the DataSource
<%# ((System.Data.Common.DbDataRecord)Container.DataItem)[0] %>
				
Visual J# .NET
// DataTable as the DataSource
<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %> 

// DataReader as the DataSource
<%# ((System.Data.Common.DbDataRecord)Container.DataItem)["au_id"] %>

// DataReader as the DataSource
<%# ((System.Data.Common.DbDataRecord)Container.DataItem)[0] %>
				
請注意,前述的範例使用 DataTable,也就是 DataSet 的子集,或是 DataReader 做為資料來源。

ItemDataBound 事件

您也可以使用控制項的 ItemDataBound 事件來繫結資料。當資料繫結至控制項時,就會發生這個事件。下列 HTML 程式碼範例使用 ItemTemplate 定義 Repeater 控制項:
<asp:repeater id=rptr runat=server>
   <itemtemplate>
      <asp:label id=lblAuthorID runat=server />
   </itemtemplate>
</asp:repeater>
				
在您的網頁中需要下列方法:

Visual Basic .NET
public Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
  
   'TODO: Retrieve data from a database,
   'and bind the data to a list control.

End Sub

public Sub rptr_OnItemDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptr.ItemDataBound
   Dim rec As DataRowView
   rec = e.Item.DataItem

   'Make sure that you have the data.
   If Not IsDBNull(rec) Then
      Dim l1 As Label
      l1 = e.Item.FindControl("lblAuthorID")
      l1.Text = rec("au_id").ToString()
   End If
End Sub
				
Visual C# .NET
public void Page_Init(object sender, System.EventArgs e)
{
   rptr.ItemDataBound += new RepeaterItemEventHandler(rptr_OnItemDataBound);
}
public void Page_Load(object sender, System.EventArgs e)
{
   // TODO: Retrieve data from a database,
   // and bind the data to a list control.
}
public void rptr_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
   System.Data.Common.DbDataRecord rec = (System.Data.Common.DbDataRecord)
                                          e.Item.DataItem;
   if(rec!=null) //Make sure that you have the data.
   {
      Label l1 = (Label)e.Item.FindControl("lblAuthorID");
      l1.Text = rec["au_id"].ToString();
   }
}
				
Visual J# .NET
public void Page_Init(Object sender, System.EventArgs e)
{
            rptr.add_ItemDataBound(new RepeaterItemEventHandler(rptr_OnItemDataBound));
}
private void Page_Load(Object sender, System.EventArgs e)
{
            // TODO: Retrieve data from a database,
            // and bind the data to a list control.
}
public void rptr_OnItemDataBound(Object sender, RepeaterItemEventArgs e)
{
            System.Data.Common.DbDataRecord rec = (System.Data.Common.DbDataRecord)
                                                   e.get_Item().get_DataItem();
            if (rec != null) //Make sure that you have the data.
            {
                        Label l1 = (Label)e.get_Item().FindControl("lblAuthorID");
                        l1.set_Text(((rec.get_Item("au_id")).ToString()));
            }
}
				

?考

如需更多有關 ASP.NET 的一般資訊,請參閱下列 MSDN 新聞群組:
microsoft.public.dotnet.framework.aspnet (http://go.microsoft.com/fwlink/?linkid=5811&clcid=0x409)

這篇文章中的資訊適用於:
  • Microsoft ASP.NET 1.0
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual J# .NET 2003 Standard Edition
  • Microsoft ASP.NET 1.1
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2003 標準版
關鍵字:?
kbarttyperoadmap kbdatabinding kbinfo kbservercontrols KB307860
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

文章翻譯