[VB.NET] การ UnBound Data บน DataGridView เพื่อจัดรูปแบบการแสดงผลฟิลด์ข้อมูล
http://www.g2gnet.com/webboard/images/vbnet/unbounddatagrid.pngพอดีแอดมินแอดมินได้รับโจทย์จากลูกค้ามา ให้รวมข้อมูล 3 ฟิลด์เข้าหากันเพื่อแสดงผลในหลักเดียวกันของตารางกริด โดยจะประกอบด้วยฟิลด์ที่อยู่ (Address), อำเภอ (Amphur) และจังหวัด (Province) ดูๆแล้วก็ไม่น่าจะมีปัญหาอะไรเนาะ แต่ทว่าการออกแบบตารางข้อมูลของแอดมิน จะทำการแยกชื่อจังหวัดออกไปอยู่อีกตารางต่างหาก แล้วมันมีปัญหาตรงไหน? เพราะเราสามารถเอาฟิลด์ข้อมูลมาจัดเรียงต่อกันใน Query ก็ได้นี่ ก็เพราะเนื่องจากว่าจังหวัดที่เป็นกรุงเทพมหานคร ต้องใช้คำว่าเขตแทนอำเภอ และจะต้องไม่มีคำนำหน้าว่าจังหวัด เอาล่ะซิทีนี้บันเทิงกันเลย หากเราไปใช้เงื่อนไขใน Query ... แอดมินเลยได้จังหวะนำเสนอการ UnBound Data เพื่อมาช่วยแก้ปัญหาในเรื่องนี้ขอรับกระผม
โดยปกติเราก็มักจะใช้วิธีการ Bound Data กันอยู่บ่อยๆ ซึ่งบางคนก็อาจจะรู้ หรือบางคนก็แทบจะไม่รู้จักเลยซ่ะด้วยซ้ำ แอดมินขอนำเสนอด้วยโค้ดแทนคำอธิบายดีกว่าครับ ...
โค้ดในส่วนของการผูกฟิลด์ข้อมูลเอาไว้ให้กับ DataTable ...
' / --------------------------------------------------------------------
' / อ่านข้อมูลจากฟิลด์ที่ระบุหรือต้องการ เข้ามาเก็บไว้ยัง DataTable
Private Function GetDataTable() As DataTable
Dim strSQL As String = _
" SELECT tblCustomer.CustomerPK, tblCustomer.CustomerID, tblCustomer.CustomerName, " & _
" tblCustomer.Address, tblCustomer.Amphur, tblCustomer.ProvinceFK, tblProvince.ProvinceName, tblCustomer.PostCode " & _
" FROM tblCustomer INNER JOIN tblProvince ON tblCustomer.ProvinceFK = tblProvince.ProvincePK " & _
" ORDER BY CustomerPK "
'/
Dim tbl As New DataTable
'// เพิ่มหลักเข้าสู่ DataTable
tbl.Columns.Add("CustomerPK", GetType(Integer))
tbl.Columns.Add("CustomerID", GetType(String))
tbl.Columns.Add("CustomerName", GetType(String))
tbl.Columns.Add("Address", GetType(String))
'//
If Conn.State = ConnectionState.Closed Then Conn.Open()
Dim Cmd = New OleDbCommand(strSQL, Conn)
Dim DR As OleDbDataReader = Cmd.ExecuteReader
While DR.Read()
If DR.HasRows Then
tbl.Rows.Add(New Object() { _
DR.Item("CustomerPK").ToString, _
DR.Item("CustomerID").ToString, _
DR.Item("CustomerName").ToString, _
GetAddress(DR.Item("Address").ToString, DR.Item("Amphur").ToString, DR.Item("ProvinceName").ToString, DR.Item("PostCode").ToString, DR.Item("ProvinceFK").ToString)})
End If
End While
DR.Close()
Cmd.Dispose()
'/ RETURN
Return tbl
End Function
มาดูโค้ดกันเถอะ ...
' / --------------------------------------------------------------------
' / 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)
' / More: http://www.g2gnet.com/webboard
' /
' / Purpose: Unbound Data method and bring the data fields together.
' / Microsoft Visual Basic .NET (2010) + MS Access 2007+
' /
' / This is open source code under @CopyRight by Thongkorn Tubtimkrob.
' / You can not distribute this code for free. Without the consent of the developer.
' / --------------------------------------------------------------------
Imports System.Data.OleDb
Public Class frmUnboundDataGrid
Dim Conn As New OleDbConnection
' / --------------------------------------------------------------------
' / Start here.
Private Sub frmUnboundDataGrid_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim strPathData As String = Application.StartupPath
strPathData = MyPath(strPathData) & "data\"
'// Connect DataBase.
Call ConnectDataBase(strPathData)
'// Load Data into the DataGridView1.
Me.DataGridView1.DataSource = GetDataTable()
'// Initialize DataGridView
Call SetupDataGridView(DataGridView1)
End Sub
' / --------------------------------------------------------------------
' / อ่านข้อมูลจากฟิลด์ที่ระบุหรือต้องการ เข้ามาเก็บไว้ยัง DataTable
Private Function GetDataTable() As DataTable
Dim strSQL As String = _
" SELECT tblCustomer.CustomerPK, tblCustomer.CustomerID, tblCustomer.CustomerName, " & _
" tblCustomer.Address, tblCustomer.Amphur, tblCustomer.ProvinceFK, tblProvince.ProvinceName, tblCustomer.PostCode " & _
" FROM tblCustomer INNER JOIN tblProvince ON tblCustomer.ProvinceFK = tblProvince.ProvincePK " & _
" ORDER BY CustomerPK "
'/
Dim tbl As New DataTable
'// เพิ่มหลักเข้าสู่ DataTable
tbl.Columns.Add("CustomerPK", GetType(Integer))
tbl.Columns.Add("CustomerID", GetType(String))
tbl.Columns.Add("CustomerName", GetType(String))
tbl.Columns.Add("Address", GetType(String))
'//
If Conn.State = ConnectionState.Closed Then Conn.Open()
Dim Cmd = New OleDbCommand(strSQL, Conn)
Dim DR As OleDbDataReader = Cmd.ExecuteReader
While DR.Read()
If DR.HasRows Then
tbl.Rows.Add(New Object() { _
DR.Item("CustomerPK").ToString, _
DR.Item("CustomerID").ToString, _
DR.Item("CustomerName").ToString, _
GetAddress(DR.Item("Address").ToString, DR.Item("Amphur").ToString, DR.Item("ProvinceName").ToString, DR.Item("PostCode").ToString, DR.Item("ProvinceFK").ToString)})
End If
End While
DR.Close()
Cmd.Dispose()
'/ RETURN
Return tbl
End Function
' / --------------------------------------------------------------------
'// รับค่าค่าเข้ามายังฟังค์ชั่น เพื่อจัดการแสดงผล
Private Function GetAddress(ByVal Address As String, ByVal Amphur As String, ByVal Province As String, ByVal PostCode As String, ByVal ProvinceFK As Integer) As String
GetAddress = String.Empty
'// จังหวัดที่ไม่ใช่กรุงเทพ (ProvinceFK = 3 คือ กรุงเทพมหานคร)
If Val(ProvinceFK) <> 3 Then
If Amphur <> "" And Province <> "" Then
GetAddress = Address & " อ." & Amphur & " จ." & Province & " " & PostCode
ElseIf Amphur <> "" And Province = "" Then
GetAddress = Address & " อ." & Amphur & " " & PostCode
ElseIf Amphur = "" And Province <> "" Then
GetAddress = Address & " จ." & Province & " " & PostCode
Else
GetAddress = Address
End If
'// กรุงเทพ
Else
If Amphur <> "" And Province <> "" Then
GetAddress = Address & " เขต" & Amphur & " " & Province & " " & PostCode
ElseIf Amphur <> "" And Province = "" Then
GetAddress = Address & " เขต" & Amphur & " " & PostCode
ElseIf Amphur = "" And Province <> "" Then
GetAddress = Address & " " & Province & " " & PostCode
Else
GetAddress = Address
End If
End If
'// คืนค่า
Return GetAddress
End Function
' / --------------------------------------------------------------------
' / Initialize DataGridView.
Private Sub SetupDataGridView(ByRef DGV As DataGridView)
With DGV
.RowHeadersVisible = True ' False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.AllowUserToResizeRows = False
.MultiSelect = False
.ReadOnly = True
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
'/ Autosize Column
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
.AutoResizeColumns()
'// Even-Odd Color
.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
'// Font data rows.
.Font = New Font("Tahoma", 9)
End With
'/ Adjust Header Styles
With DGV
With .ColumnHeadersDefaultCellStyle
.BackColor = Color.Navy
.ForeColor = Color.Black
.Font = New Font("Tahoma", 9, FontStyle.Bold)
End With
End With
'// Customize the header.
With DGV
With .Columns(0)
.Name = "CustomerPK"
.HeaderText = "CustomerPK"
.Visible = False
End With
With .Columns(1)
.Name = "CustomerID"
.HeaderText = "รหัสลูกค้า"
.ReadOnly = True
End With
With .Columns(2)
.Name = "CustomerName"
.HeaderText = "ชื่อลูกค้า"
End With
With .Columns(3)
.Name = "Address"
.HeaderText = "ที่อยู่"
End With
End With
End Sub
' / --------------------------------------------------------------------
' / Connect Database.
Sub ConnectDataBase(ByVal PathData As String)
Dim strConn As String = _
"Provider = Microsoft.ACE.OLEDB.12.0; " & _
" Data Source = " & PathData & "MyDB.accdb;"
Try
Conn = New OleDbConnection(strConn)
'// Test Connection
Conn.Open()
'MsgBox("Connection Complete.")
Catch ex As Exception
MessageBox.Show(ex.Message, "ERROR")
End
End Try
End Sub
' / --------------------------------------------------------------------
' / Config path.
Function MyPath(ByVal AppPath As String) As String
AppPath = AppPath.ToLower
AppPath = AppPath.Replace("\bin\debug", "").Replace("\release\debug", "").Replace("\bin\x86\debug", "")
If Microsoft.VisualBasic.Right(AppPath, 1) <> "\" Then AppPath = AppPath & "\"
Return AppPath
End Function
Private Sub frmUnboundDataGrid_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Dispose()
Application.Exit()
End Sub
End Class
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
หน้า:
[1]