ASP.Netのお勉強

GridViewのDataSourceに配置@ASP.Net

SqlDataSourceを用いたGridViewの表示を書きましたが、
DataTableを作成し、DataSourceに配置して表示する方法です。

DBに接続し、SQL文を発行して結果を取得します。
結果を元にDataTableを作成します。

GridViewのDataSourceにDataTableを設定します。
DataBindを行います。

●aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" Inherits="test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>View</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>


●vb

Imports System.Data.SqlClient
Imports System.Data

Partial Class test
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dbcon As SqlConnection
        Dim dbcmd As SqlCommand
        Dim dataRead As SqlDataReader

        Dim dt As DataTable
        Dim dr As DataRow

        Dim sqlStr As String
        Dim sqlUrl As String

            '接続文字列
            sqlUrl = "data source=(local)\SQLEXPRESS;initial catalog=DB;user id=id;password=pass;persist security info=True;packet size=4096"

            'DBコネクション作成
            dbcon = New SqlConnection(sqlUrl)

            'DB接続
            dbcon.Open()

            'SQL文(NOの降順で取得)
            sqlStr = "SELECT ID,NAME FROM TABLE"

            'SQLコマンド作成
            dbcmd = New SqlCommand(sqlStr, dbcon)

            'SQL文実行
            dataRead = dbcmd.ExecuteReader()

            'データテーブル作成
            dt = New DataTable()

            dt.Columns.Add(New DataColumn("ID", GetType(String)))
            dt.Columns.Add(New DataColumn("NAME", GetType(String)))

            '結果を読み込み
            Dim bbsStr As String = ""
            While (dataRead.Read())
                dr = dt.NewRow()

                dr(0) = dataRead("ID")
                dr(1) = dataRead("NAME")
                dt.Rows.Add(dr)
            End While

            'DataSourceに設置
            Me.GridView1.DataSource = dt.DefaultView
            Me.GridView1.DataBind()

            'DBクローズ処理
            dataRead.Close()
            dbcmd.Dispose()
            dbcon.Close()
            dbcon.Dispose()
    End Sub
End Class

Copyright (C) ASP.Netのお勉強. All Rights Reserved.