[ASP.NET][VB.NET]GridView的基本使用方法-1

摘要:GridView的基本使用方法-1(語法VB.NET)




設計頁面

新增一個按鈕Button1與一個按鈕GridView1


第一次開啟網頁時只有一個按鈕Button


當按鈕被按下去時,被處發後的按鈕會去連線到資料庫內

把所需要的資料內容載入進來


使用VB.NET的語法編寫的,原始碼如下方,僅供各位參考!!


Imports System.Data.SqlClient

Public Class WebForm2
    Inherits System.Web.UI.Page

    Public Conn As New SqlConnection()    '宣告SQL的連線
    Public cmd As New SqlCommand()        '宣告對SQL執行的語法
    Public da As New SqlDataAdapter()     'SQL 資料庫的連接與執行命令
    Public ds As New DataSet()            '宣告一個資料表存放在暫存記憶體內

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'PostBack後停留在原畫面
        Page.MaintainScrollPositionOnPostBack = True
    End Sub

    Protected Sub txtCustomers()
        Try      'try 區塊中含有可能會導致例外狀況並受到嚴密監控的程式碼

            ds.Tables("Customers").Clear()            '清除DataSet裡的資料內容
        Catch
            cmd.Connection = Conn            '將SQL執行的命令語法程式CMD與CONN與SQL連接

            '設定連線IP位置、資料表,帳戶,密碼
            Conn.ConnectionString = "Data Source=127.0.0.1;Initial Catalog=NorthwindChinese;Persist Security Info=True"
            '這一行可依連線的字串不同而去定義它該連線到哪個資料庫!!

            cmd.CommandText = "SELECT CustomerID,CompanyName,ContactName,Address FROM Customers"            '執行SQL語法進行查詢
            da.SelectCommand = cmd            'da選擇資料來源,由cmd載入進來
            da.Fill(ds, "Customers")            'da把資料填入ds裡面
        End Try
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        txtCustomers()                   '呼叫副程式
        GridView1.DataSource = ds        '將DataSet的資料載入到GridView1內
        GridView1.DataBind()             '將資料繫結到GridView1內
    End Sub
End Class