將 SQL 資料繫結至 DataGrid 控制項
DataGrid 伺服器控制項具有多項用途,能以表格顯示資料,並支援選擇、排序和編輯資料。DataGrid 依預設會替資料來源中的每個欄位產生繫結資料行 (AutoGenerateColumns=true)。每個資料欄位會依照在資料庫中儲存的順序,顯示在個別資料行中。下列範例顯示作者名稱、地址、電話和其他資料的清單。如需參考類似的範例執行,請於 ASP.NET 快速入門執行 DataGrid1.aspx 範例。
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="VB" runat="server">
Sub Page_Load(Src As Object, e As EventArgs)
Dim myConnection As SqlConnection
Dim myCommand As SqlDataAdapter
' Create a connection to the "pubs" SQL database located on the
' local computer.
myConnection = New SqlConnection("server=localhost;" _
& "database=pubs;Trusted_Connection=Yes")
' Connect to the SQL database using a SQL SELECT query to get all
' the data from the "Authors" table.
myCommand = new SqlDataAdapter("SELECT * FROM Authors", _
myConnection)
' Create and fill a DataSet.
Dim ds As DataSet = new DataSet()
myCommand.Fill(ds)
' Bind MyDataGrid to the DataSet. MyDataGrid is the
' ID for the DataGrid control in the HTML section.
MyDataGrid.DataSource = ds
MyDataGrid.DataBind()
End Sub
</script>
<body>
<h3><font face="Verdana">
Simple Select to a DataGrid Control.
</font></h3>
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false"
/>
</body>
</html>
[C#]
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="C#" runat="server">
protected void Page_Load(Object Src, EventArgs E)
{
// Create a connection to the "pubs" SQL database located on the
// local computer.
SqlConnection myConnection = new SqlConnection("server=localhost;" +
"database=pubs;Trusted_Connection=Yes");
// Connect to the SQL database using a SQL SELECT query to get all
// the data from the "Authors" table.
SqlDataAdapter myCommand = new SqlDataAdapter("SELECT " +
" * FROM Authors", myConnection);
// Create and fill a DataSet.
DataSet ds = new DataSet();
myCommand.Fill(ds);
// Bind MyDataGrid to the DataSet. MyDataGrid is the ID for the
// DataGrid control in the HTML section.
DataView source = new DataView(ds.Tables[0]);
MyDataGrid.DataSource = source ;
MyDataGrid.DataBind();
}
</script>
<body>
<%-- Display the DataGrid information in the body of the page. --%>
<h3><font face="Verdana">Simple SELECT to a DataGrid Control
</font></h3>
<%-- Display the data in a DataGrid. --%>
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false"
/>
</body>
</html>
請參閱
使用 ASP.NET 存取資料 | 使用 ADO.NET 存取資料 | System.Web.UI.WebControls 命名空間 | DataGrid 控制項