thongkorn โพสต์ 2017-10-23 14:21:38

[VB.NET] พื้นฐานการนำข้อมูลจาก DataBase มาแสดงผลบนตารางกริด (DataSet)

http://www.g2gnet.com/webboard/images/vbnet/BindDataGrid.png
สวัสดีครับพี่น้องหมู่เฮาชุมชนคนรักภาษาเบสิค วันนี้ก็มาแจกโค้ดแบบพื้นๆบ้านๆ แต่เป็นหลักการขั้นพื้นฐานที่จะนำทางให้พี่น้องได้ก้าวไปข้างหน้า ในการฝึกฝนเรียนรู้พัฒนาโปรแกรมด้วย Visual Basic .NET ด้วย การนำข้อมูลจาก DataBase มาแสดงผลบน DataGrid ในลักษณะที่เรียกกันว่า Bound Data หรือ การผูกข้อมูลเข้ากับคอนโทรล (DataGrid) แต่จะเป็นแบบ @Run Time Programming คือการใช้โค้ดเพื่อสั่งรันโปรแกรม มันจึงจะเห็นผล การเขียนโค้ดในลักษณะนี้ จะแตกต่างไปจากการจับลากมาวาง หรือที่เรียกว่า @Design Time เพราะเราจะสามารถควบคุมการทำงานของโปรแกรมให้เป็นไปในทิศทางที่เราต้องการได้ข่ะรับ ...
มารู้จักกับคำว่า Bound และ UnBound Control

[*]Bound Control ... คือการผูก (Bound) ตารางข้อมูลเข้ากับพวก Component หรือ Control ต่างๆ กรณีที่นำมาใช้แสดงผลลงในตารางกริด มันจะอ่านค่าฟิลด์ต่างๆ เพื่อแสดงผลในแต่ละหลัก เรียงตามลำดับจาก Query ที่เราเขียนไว้ และ ต้องแสดงทุกๆฟิลด์ออกมาทั้งหมด มักจะนำไปแสดงผลข้อมูล การป้อนข้อมูล และอัพเดตค่าจากฟิลด์ต่างๆในฐานข้อมูล
[*]UnBound Control ก็จะไม่มีการผูก (Unbound) ตารางข้อมูลใดๆเข้ากับ Component หรือ Control การนำไปใช้ในตารางกริด ไม่จำเป็นต้องแสดงผลออกมาทุกฟิลด์ โดยจะเอาตัวไหนมาแสดงผลในหลักใดๆของตารางกริดก่อนหลังก็ได้ มีความยืดหยุ่น มักใช้กับการเข้าไปแก้ไขข้อมูลตารางกริดในแต่ละเซลล์ เช่น การคำนวณ หรือการป้อนข้อมูลที่มีลักษณะแบบไม่ตายตัว
Dim DA As New OleDb.OleDbDataAdapter(Sql, Conn)
      Dim DS As New DataSet
      DA.Fill(DS)
      dgvData.DataSource = DS.Tables(0)โค้ดในส่วนนี้นี่แหละคือ การผูกข้อมูล หรือ Bound Data

มาดูโค้ดกันเถอะ ...
' / --------------------------------------------------------------------------------
' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
' / eMail : thongkorn@hotmail.com
' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
' / Facebook: https://www.facebook.com/commonindy (Worldwide)
' / Purpose: Simple procedure to binding data into datagridview. (Call Bound Data)
' / Microsoft Visual Basic .NET (2010) + MS Access
' /
' / This is open source code under @Copyleft by Thongkorn Tubtimkrob.
' / You can modify and/or distribute without to inform the developer.
' / --------------------------------------------------------------------------------
Imports System.Data.OleDb
Imports Microsoft.VisualBasic

Public Class frmDataBinding
    Dim Conn As OleDbConnection
    Dim strPath As String = MyPath(Application.StartupPath)

    ' / --------------------------------------------------------------------------------
    '// Initialize DataGridView @Run Time
    Private Sub InitDataGrid()
      With dgvData
            .RowHeadersVisible = False
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToResizeRows = False
            .MultiSelect = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .ReadOnly = True
            .Font = New Font("Tahoma", 9)
            '// Autosize Column
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
            .AutoResizeColumns()
            '// Even-Odd Color
            .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
            ' Adjust Header Styles
            With .ColumnHeadersDefaultCellStyle
                .BackColor = Color.Navy
                .ForeColor = Color.Black
                .Font = New Font("Tahoma", 9, FontStyle.Bold)
            End With
      End With
    End Sub

    ' / --------------------------------------------------------------------------------
    Private Sub btnBrowse_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
      Dim OpenFile As New OpenFileDialog()
      '// Specifies the initial path.
      OpenFile.InitialDirectory = strPath
      OpenFile.FileName = ""
      '// Set to filter only files MS Access (*.accdb;*.mdb)
      OpenFile.Filter = "Microsoft Access Files |*.accdb;*.mdb"

      '// Reference
      '// http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx
      '// http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult.aspx
      Dim Res As System.Windows.Forms.DialogResult = OpenFile.ShowDialog()
      ' Press Cancel to leave.
      If Res = System.Windows.Forms.DialogResult.Cancel Then Return

      '// Bring path and filename to display in TextBox.
      txtLocateDB.Text = OpenFile.FileName
      '//
      If txtLocateDB.Text.Length = 0 Or Trim(txtLocateDB.Text) = "" Then Return
      '// Connect MS Access with your select file.
      If ConnectDataBase(txtLocateDB.Text) Then
            lblStatus.Text = "Connection ..."
            lblStatus.ForeColor = Color.Green
      Else
            lblStatus.Text = "Disconnection ..."
            lblStatus.ForeColor = Color.Red
      End If
    End Sub

    ' / --------------------------------------------------------------------------------
    '// Return True if can connect, otherwise is False.
    Public Function ConnectDataBase(ByVal DBFile As String) As Boolean
      Dim strConn As String = _
                "Provider = Microsoft.ACE.OLEDB.12.0; "
      strConn += "Data Source = " & DBFile
      Try
            Conn = New OleDb.OleDbConnection(strConn)
            '// Create Connection
            Conn.ConnectionString = strConn
            Conn.Open()
            '// Return
            Return True
      Catch ex As Exception
            'MessageBox.Show(ex.Message)
            Return False
      End Try
    End Function

    ' / --------------------------------------------------------------------------------
    ' / Get my project path
    ' / AppPath = C:\My Project\bin\debug
    ' / Replace "\bin\debug" with "\"
    ' / Return : C:\My Project\
    Function MyPath(ByVal AppPath As String) As String
      '/ MessageBox.Show(AppPath);
      AppPath = AppPath.ToLower()
      '/ Return Value
      MyPath = AppPath.Replace("\bin\debug", "\").Replace("\bin\release", "\").Replace("\bin\x86\debug", "\")
      '// If not found folder then put the \ (BackSlash) at the end.
      If Microsoft.VisualBasic.Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
    End Function

    Private Sub txtLocateDB_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtLocateDB.KeyPress
      '// Can't press any key into Textbox.
      e.Handled = True
    End Sub

    Private Sub frmDataBinding_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      Me.Dispose()
      Application.Exit()
    End Sub

    ' / --------------------------------------------------------------------------------
    Private Sub frmDataBinding_Load(sender As Object, e As System.EventArgs) Handles Me.Load
      '// Initialize DataGridView
      Call InitDataGrid()
      '// Sample SQL Statement
      txtSQL.Text = "SELECT ContactPK, Fullname, Nickname, Mobile, Phone, eMail, LineID FROM tblContact ORDER BY ContactPK "
      'txtSQL.Text = "SELECT ContactPK, Fullname, NickName, Mobile, eMail FROM tblContact WHERE Fullname LIKE '%T%' ORDER BY ContactPK"
      lblStatus.Text = "Disconnection ..."
      lblStatus.ForeColor = Color.Red
    End Sub

    ' / --------------------------------------------------------------------------------
    '// BOUND DATA into DataGridView.
    Private Sub BindDataGrid(ByVal Sql As String)
      Try
            If Conn.State = ConnectionState.Closed Then Conn.Open()
            Dim DA As New OleDb.OleDbDataAdapter(Sql, Conn)
            Dim DS As New DataSet
            DA.Fill(DS)
            dgvData.DataSource = DS.Tables(0)
            '//
            DA.Dispose()
            DS.Dispose()
            Conn.Close()
            '// Addition
            With dgvData
                '// You can change the columns header @ here
                .Columns(1).HeaderText = "Column Text"
                '// If you want to turn off the display some columns.
                '.Columns("LineID").Visible = False
                '// Or count column by index
                .Columns(6).Visible = False
            End With

      Catch ex As Exception
            MessageBox.Show(ex.Message)
      End Try
    End Sub

    ' / --------------------------------------------------------------------------------
    Private Sub btnExecute_Click(sender As System.Object, e As System.EventArgs) Handles btnExecute.Click
      If txtSQL.Text.Length = 0 Or Trim(txtSQL.Text) = "" Then Return
      Call BindDataGrid(txtSQL.Text)
    End Sub

End Classดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่

thawatchai-sena โพสต์ 2017-10-28 23:44:59

ขอบคุณครับ
หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] พื้นฐานการนำข้อมูลจาก DataBase มาแสดงผลบนตารางกริด (DataSet)