多様な機能を持つ DataGrid サーバー コントロールは、表形式のデータを表示し、データの選択、並べ替え、編集をサポートします。既定では、DataGrid は、データ ソースのフィールドごとに 1 つの連結された列を生成します (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 クラス