[VB.NET] พื้นฐานการนำข้อมูลจาก DataBase มาแสดงผลบนตารางกริด (Data Reader)
http://www.g2gnet.com/webboard/images/vbnet/BindDataGridReader.pngจากภาคแรก พื้นฐานการนำข้อมูลจาก DataBase มาแสดงผลบนตารางกริด (DataSet) ด้วยการใช้ DataSet โดยการใช้โค้ดแบบ @Run Time ที่แอดมินเรียกมันว่า Bound Data จะเห็นว่ามีความสะดวกสบายและง่ายดายมากๆ แต่ทว่ามันกลับมีความยุ่งยากในการแสดงผลข้อมูลในตารางกริดจำพวกรูปภาพ (แบบเก็บชื่อไฟล์ โดยไม่ได้จับยัดภาพใส่ไว้ในฐานข้อมูล) หรือสูตรสมการ เช่น การป้อนราคาสินค้า แล้วต้องคูณกับจำนวนสินค้า (หรือกลับกัน) ดังนั้นวิธีการ Unbound Data หรือ การไม่ผูกข้อมูลใดๆเข้ากับคอนโทรล จึงถูกนำมาใช้แก้ปัญหาควบคู่กันมาตลอด ตั้งแต่ยุคสมัยรุ่นคุณปู่ทวด MS Visual Basic 4.0 เหลือเชื่อมั้ยล่ะครับทั่นผู้ชม ...
"SELECT ContactPK, Fullname, NickName, Phone FROM tblContact ORDER BY ContactPK "กรณีของ Bound Data ฟิลด์ข้อมูลต่างๆเหล่านี้ เมื่อนำไปแสดงผลใน DataGrid หลัก (Column) จะต้องถูกจัดเรียงลำดับตาม Query แต่กรณีของ Unbound Data ไม่มีความจำเป็นต้องมีการเรียงลำดับกัน แล้วยังสามารถเลือกที่จะนำมาแสดงผลในตารางกริดหรือไม่ก็ได้
'// Count fields and add columns
For iCol = 0 To DR.FieldCount - 1
With dgvData
'// Add columns.
.Columns.Add("Column" & iCol, "Column" & iCol)
End With
Nextสาระสำคัญของการ Unbound Data ก่อนที่จะนำเอาข้อมูลมาแสดงผลในตารางกริดได้ เราจะต้องรู้และตั้งค่าจำนวนหลัก (Columns) ที่มีทั้งหมดเสียก่อน ส่วนกรณีของ Bound Data จะไม่ต้องการ เพราะมันนับตาม Query เอาเลย
If DR.HasRows Then
While DR.Read
With dgvData
'// Add new row.
.Rows.Add()
'// Loop through the number of fields
For iCol = 0 To DR.FieldCount - 1
.Rows(iRow).Cells(iCol).Value = DR.Item(iCol).ToString
Next
End With
'// Next row
iRow += 1
End While
End Ifคุณลักษณะอย่างหนึ่งของการ Unbound Data จะต้องมีวิธีการทำซ้ำ (Repetitive) ... ขอให้สังเกตดีๆว่า ตัว DataGridView จะไม่มีการผูก (Bound Data) เอาไว้กับแหล่งจ่ายข้อมูล หรือ Data Source ใดๆเลย ... คงจะกระจ่างแจ้งแล้วใช่มั้ยครับท่านผู้ชม สำหรับคำว่า Bound VS UnBound
มาดูโค้ดกันเถอะ ...
' / --------------------------------------------------------------------------------
' / 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 @Run Time. (Data Reader)
' / Microsoft Visual Basic .NET (2010) + MS Access 2007+
' /
' / 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 frmDataReader
Dim Conn As OleDbConnection
Dim strPath As String = MyPath(Application.StartupPath)
' / --------------------------------------------------------------------------------
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 successful ..."
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, Phone FROM tblContact ORDER BY ContactPK "
txtSQL.Text = _
"SELECT ContactPK, Fullname, NickName, Phone FROM tblContact " & _
"WHERE Fullname LIKE '%T%' ORDER BY ContactPK ASC"
'//
lblStatus.Text = "Disconnection ..."
lblStatus.ForeColor = Color.Red
End Sub
' / --------------------------------------------------------------------------------
'// Initialize DataGridView @Run Time
Private Sub InitDataGrid()
With dgvData
.RowHeadersVisible = False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.AllowUserToResizeRows = False
.MultiSelect = False
.SelectionMode = DataGridViewSelectionMode.CellSelect
.ReadOnly = False
.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
' / --------------------------------------------------------------------------------
'// Load data into DataGridView.
Private Sub BindDataGrid(ByVal Sql As String)
Try
Dim Cmd As New OleDbCommand
If Conn.State = ConnectionState.Closed Then Conn.Open()
Cmd.Connection = Conn
Cmd.CommandText = Sql
Dim DR As OleDbDataReader = Cmd.ExecuteReader
'// Clear all columns.
dgvData.Columns.Clear()
'// Count fields and add columns
For iCol = 0 To DR.FieldCount - 1
With dgvData
'// Add columns.
.Columns.Add("Column" & iCol, "Column" & iCol)
End With
Next
'// Clear all rows.
dgvData.Rows.Clear()
Dim iRow As Integer = 0
If DR.HasRows Then
While DR.Read
With dgvData
'// Add new row.
.Rows.Add()
'// Loop through the number of fields
For iCol = 0 To DR.FieldCount - 1
.Rows(iRow).Cells(iCol).Value = DR.Item(iCol).ToString
Next
End With
'// Next row
iRow += 1
End While
End If
DR.Close()
Conn.Close()
'// You can change the columns header @ here
With dgvData
.Columns(0).HeaderText = "Primary Key"
.Columns(1).HeaderText = "Full name"
'// Other columns
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
'// Execute SQL Statement
Call BindDataGrid(txtSQL.Text)
End Sub
End ClassConclusion: ทั้งการ Bound และ Unbound Data มันเป็นพื้นฐานที่สำคัญในการแสดงผลข้อมูลในตารางกริด โดยแต่ละชนิดก็จะมีทั้งข้อดีและข้อเสีย ซึ่งเราจะต้องเลือกมันมาใช้งานให้ถูกที่ถูกเวลา การเรียนรู้ศึกษาต้องพิจารณาถึงความแตกต่างของโค้ดตัวอย่างที่แอดมินได้ให้ไป และหลักการที่ว่ามานี้ได้ถูกนำมาใช้งานตั้งแต่ MS Visual Basic 4.0 รุ่นตะลึงทั้งวงการ เพราะสามารถใช้งานบน Windows32 บิทได้อย่างสมบูรณ์
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่
:) ขอบคุณครับ อาจารย์ :):) ขอบคุณครับ อาจารย์
หน้า:
[1]