ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 25|ตอบกลับ: 0

[VB.NET] การเปรียบเทียบค่าระหว่าง DataGridView 2 ตัว (เรื่องของ Set)

[คัดลอกลิงก์]

331

กระทู้

526

โพสต์

7178

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
7178
โพสต์ เมื่อวาน 13:15 | ดูโพสต์ทั้งหมด |โหมดอ่าน




มาดูวิธีการคิด ...
1. โหลดข้อมูลจาก MS Access เข้าสู่ DataGridView1 (A)
2. โหลดข้อมูลจาก Excel เข้าสู่ DataGridView2 (B)
3. สมมุติฐานคือให้ B เป็น Subset ของ A นั่นคือสมาชิกทุกตัวของ B จะต้องเป็นสมาชิกของ A
4. วนรอบแถวทั้งหมดจาก DataGridView1 (A) เป็นหลัก เพื่อทำการเปรียบเทียบค่าในแต่ละแถว DataGridView2 (B) โดยทำการเปรียบเทียบจากหลัก 0 หากมีค่าตรงกัน เช่น 'E' = 'E' ก็ให้ทำการบวกค่าในแต่ละหลักของทั้ง 2 ตารางกริดเข้าหากัน
5. นำผลลัพธ์ที่ได้ไปแสดงผลใน DataGridView3 (C)
6. เลือกทำการบันทึกข้อมูลจาก DataGridView3 ลงไปในไฟล์ MS Access ต้นฉบับ หรือเลือกบันทึกไฟล์ใหม่

(หมายเหตุ: DataGridView4 แอดมินเพิ่มเติมให้ในทำการ Intersection คือการหาสมาชิกทั้งหมดที่เหมือนกันในเซตต้นแบบ)

มาดูโค้ดฉบับเต็มกันเถอะ ...
  1. Imports System.Data.OleDb
  2. Imports System.IO

  3. Public Class frmCompareDataGridView

  4.     Private Sub frmCompareDataGridView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  5.         Call LoadDataFromAccess()
  6.         Call LoadDataFromExcel()
  7.         '// --------------------------------------------------------------------------------------
  8.         '// ยึดค่าตาม DataGridView1 เพราะ DataGridView2 เป็น Subset ของ DataGridView1
  9.         '// นั่นคือสมาชิกทุกตัวของ DataGridView2 จะต้องเป็นสมาชิกของ DataGridView1
  10.         Call CompareDataGridView1()
  11.         '// ยึดค่าตาม DataGridView2 หรือการทำ Intersection
  12.         Call CompareDataGridView2()
  13.         '// --------------------------------------------------------------------------------------
  14.         '// Initialized All DataGridView
  15.         Call SetupGridView(DataGridView1)
  16.         Call SetupGridView(DataGridView2)
  17.         Call SetupGridView(DataGridView3)
  18.         Call SetupGridView(DataGridView4)
  19.     End Sub

  20.     '// --------------------------------------------------------------------------------------
  21.     '// โหลดข้อมูลจาก MS Access เข้าไปที่ DataGridView1
  22.     Private Sub LoadDataFromAccess()
  23.         Dim Conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & MyPath(Application.StartupPath) & "\MyData.accdb")
  24.         Dim sql As String = "SELECT * FROM Table1"
  25.         Dim Cmd As OleDbCommand
  26.         Dim DR As OleDbDataReader
  27.         Cmd = New OleDbCommand(sql, Conn)
  28.         With DataGridView1.Columns
  29.             .Add("c1", "Name")
  30.             .Add("c2", "SCB")
  31.             .Add("c3", "KTB")
  32.             .Add("c4", "TMB")
  33.             .Add("c5", "UOB")
  34.         End With
  35.         Try
  36.             If Conn.State = ConnectionState.Open Then Conn.Close()
  37.             Conn.Open()
  38.             DR = Cmd.ExecuteReader
  39.             DataGridView1.Rows.Clear()
  40.             While DR.Read
  41.                 DataGridView1.Rows.Add(DR(0), DR(1), DR(2), DR(3), DR(4))
  42.             End While
  43.         Catch ex As Exception
  44.             MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
  45.         Finally
  46.             Cmd.Dispose()
  47.             Conn.Close()
  48.         End Try
  49.     End Sub

  50.     '// --------------------------------------------------------------------------------------
  51.     '// โหลดข้อมูลจาก Excel เข้าไปที่ DataGridView2
  52.     Private Sub LoadDataFromExcel()
  53.         Dim Conn As OleDbConnection
  54.         Dim Cmd As OleDbCommand
  55.         Dim DA As New OleDbDataAdapter
  56.         Dim strConn As String = _
  57.             " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
  58.             MyPath(Application.StartupPath) & "MyData.xlsx" & ";" & _
  59.             " Extended Properties=""Excel 12.0 Xml; HDR=YES"";"
  60.         Try
  61.             Me.DataGridView2.DataSource = Nothing
  62.             Dim DT As New DataTable
  63.             Conn = New OleDbConnection
  64.             Conn.ConnectionString = strConn
  65.             Cmd = New OleDbCommand
  66.             '/ เสมือน Sheet เป็น Table ในฐานข้อมูล
  67.             Cmd.CommandText = "Select * FROM [Sheet1$]"
  68.             Cmd.Connection = Conn
  69.             DA.SelectCommand = Cmd
  70.             DA.Fill(DT)
  71.             DataGridView2.DataSource = DT
  72.             '//
  73.         Catch ex As Exception
  74.             MessageBox.Show(ex.Message)
  75.         Finally
  76.             Conn = Nothing
  77.             Cmd = Nothing
  78.             DA = Nothing
  79.         End Try
  80.     End Sub

  81.     '// --------------------------------------------------------------------------------------
  82.     '// จะทำการลูปตามจำนวนแถวของ DataGridView1 เพื่อเปรียบเทียบกับค่าในแถวของ DataGridView2
  83.     '// หากหลักแรก (Index = 0) มีค่าตรงกัน เช่น 'A' = 'A' ก็จะทำการบวกค่าในแต่ละหลักของแถวที่ตรงกันไปแสดงผลที่ DataGridView3
  84.     Private Sub CompareDataGridView1()
  85.         DataGridView3.Rows.Clear()
  86.         DataGridView3.Columns.Clear()
  87.         '// สร้างคอลัมน์ใน DataGridView3
  88.         With DataGridView3.Columns
  89.             .Add("Name", "Name")
  90.             .Add("SCB", "SCB")
  91.             .Add("KTB", "KTB")
  92.             .Add("TMB", "TMB")
  93.             .Add("UOB", "UOB")
  94.         End With
  95.         '// วนลูปผ่าน DataGridView1
  96.         For Each row1 As DataGridViewRow In DataGridView1.Rows
  97.             If row1.IsNewRow Then Continue For '<-- ข้ามแถวว่างสุดท้าย ถ้าไม่ได้ปิด AllowUserToAddRows = False
  98.             '// ใช้การอ้างอิงหลักผ่าน Index แทนการระบุชื่อ
  99.             Dim name1 As String = row1.Cells(0).Value.ToString()
  100.             Dim scb1 As Integer = Convert.ToInt32(row1.Cells(1).Value)
  101.             Dim ktb1 As Integer = Convert.ToInt32(row1.Cells(2).Value)
  102.             Dim tmb1 As Integer = Convert.ToInt32(row1.Cells(3).Value)
  103.             Dim uob1 As Integer = Convert.ToInt32(row1.Cells(4).Value)
  104.             '// ค่ารวมจาก DataGridView2
  105.             Dim scb2 As Integer = 0
  106.             Dim ktb2 As Integer = 0
  107.             Dim tmb2 As Integer = 0
  108.             Dim uob2 As Integer = 0
  109.             '// วนลูปผ่าน DataGridView2 เพื่อตรวจสอบจากหลัก 0 ที่ตรงกัน เช่น 'A' = 'A'
  110.             For Each row2 As DataGridViewRow In DataGridView2.Rows
  111.                 If row2.IsNewRow Then Continue For
  112.                 Dim dname As String = row2.Cells("dName").Value.ToString()
  113.                 If dname = name1 Then
  114.                     scb2 += Convert.ToInt32(row2.Cells("SCB").Value)
  115.                     ktb2 += Convert.ToInt32(row2.Cells("KTB").Value)
  116.                     tmb2 += Convert.ToInt32(row2.Cells("TMB").Value)
  117.                     uob2 += Convert.ToInt32(row2.Cells("UOB").Value)
  118.                 End If
  119.             Next
  120.             '// รวมค่า
  121.             Dim totalSCB = scb1 + scb2
  122.             Dim totalKTB = ktb1 + ktb2
  123.             Dim totalTMB = tmb1 + tmb2
  124.             Dim totalUOB = uob1 + uob2
  125.             '// เพิ่มข้อมูลเข้า DataGridView3
  126.             DataGridView3.Rows.Add(name1, totalSCB, totalKTB, totalTMB, totalUOB)
  127.         Next
  128.     End Sub

  129.     '// --------------------------------------------------------------------------------------
  130.     '// จะทำการลูปตามจำนวนแถวของ DataGridView2 เพื่อเปรียบเทียบกับค่าในแถวของ DataGridView1
  131.     '// หากหลักแรก (Index = 0) มีค่าตรงกัน เช่น 'A' = 'A' ก็จะทำการบวกค่าในแต่ละหลักของแถวที่ตรงกันไปแสดงผลที่ DataGridView4
  132.     Private Sub CompareDataGridView2()
  133.         '// คัดลอกคอลัมน์จาก DataGridView2 (เพราะยึดจาก DGV2)
  134.         For Each col As DataGridViewColumn In DataGridView2.Columns
  135.             DataGridView4.Columns.Add(DirectCast(col.Clone(), DataGridViewColumn))
  136.         Next
  137.         '// วนลูปแถวใน DataGridView2
  138.         For Each row2 As DataGridViewRow In DataGridView2.Rows
  139.             If row2.IsNewRow Then Continue For
  140.             Dim resultRow As New List(Of Object)
  141.             Dim name2 As String = row2.Cells(0).Value.ToString()
  142.             '// คัดลอกค่าเดิมจาก DataGridView2 ลง resultRow
  143.             resultRow.Add(name2)
  144.             For i As Integer = 1 To 4
  145.                 resultRow.Add(Val(row2.Cells(i).Value))
  146.             Next
  147.             '// ตรวจสอบชื่อกับ DataGridView1 และบวกค่าหากเจอ
  148.             For Each row1 As DataGridViewRow In DataGridView1.Rows
  149.                 If row1.IsNewRow Then Continue For
  150.                 Dim name1 As String = row1.Cells(0).Value.ToString()
  151.                 If name2 = name1 Then
  152.                     For i As Integer = 1 To 4
  153.                         Dim currentVal As Decimal = Convert.ToDecimal(resultRow(i))
  154.                         Dim addVal As Decimal = Val(row1.Cells(i).Value)
  155.                         resultRow(i) = currentVal + addVal
  156.                     Next
  157.                     Exit For '// เจอแล้วหยุด
  158.                 End If
  159.             Next
  160.             '// เพิ่มข้อมูลรวมลงใน DataGridView4
  161.             DataGridView4.Rows.Add(resultRow.ToArray())
  162.         Next
  163.     End Sub

  164.     '// --------------------------------------------------------------------------------------
  165.     '// บันทึกข้อมูลจาก DataGridView3 ลงไปยังไฟล์ MS Access ที่ถูกสร้างขึ้นใหม่
  166.     Private Sub btnSaveNewFile_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveNewFile.Click
  167.         '// ==== 1. เลือกชื่อและตำแหน่งไฟล์ Access ที่จะสร้างใหม่ ====
  168.         Dim SaveDialog As New SaveFileDialog()
  169.         With SaveDialog
  170.             .InitialDirectory = MyPath(Application.StartupPath)
  171.             .Filter = "Access Database (*.accdb)|*.accdb"
  172.             .Title = "บันทึกข้อมูลเป็น Access Database"
  173.             .FileName = "Data_" & DateTime.Now.ToString("ddMMyyyy_HHmmss") & ".accdb"
  174.         End With
  175.         If SaveDialog.ShowDialog() <> DialogResult.OK Then Exit Sub
  176.         '// ตำแหน่งไฟล์และชื่อไฟล์+นามสกุล
  177.         Dim DbPath As String = SaveDialog.FileName
  178.         '// ชื่อไฟล์+นามสกุล
  179.         Dim DbFileName As String = System.IO.Path.GetFileName(SaveDialog.FileName)

  180.         '// ==== 2. สร้างไฟล์ .accdb ใหม่ ====
  181.         If File.Exists(DbPath) Then File.Delete(DbPath)
  182.         Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DbPath & ";Jet OLEDB:Engine Type=5;"
  183.         Dim Cat = CreateObject("ADOX.Catalog")
  184.         Cat.Create(strConn)

  185.         '// ==== 3. สร้างตารางใหม่โดยอิงจากคอลัมน์ของ DataGridView1 ====
  186.         Dim TableName As String = "Table1"
  187.         Using Conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DbPath)
  188.             Conn.Open()
  189.             '// สร้างคำสั่ง SQL สำหรับสร้างตาราง
  190.             Dim Sql As String = "CREATE TABLE [" & TableName & "] ("
  191.             For i As Integer = 0 To DataGridView1.Columns.Count - 1
  192.                 Dim colName = DataGridView1.Columns(i).HeaderText
  193.                 If i = 0 Then
  194.                     Sql &= "[" & colName & "] TEXT(255),"
  195.                 Else
  196.                     Sql &= "[" & colName & "] SMALLINT,"
  197.                 End If
  198.             Next
  199.             '// ลบ comma สุดท้าย และปิดวงเล็บ
  200.             Sql = Sql.TrimEnd(","c) & ")"
  201.             Using Cmd As New OleDbCommand(Sql, Conn)
  202.                 Cmd.ExecuteNonQuery()
  203.             End Using

  204.             '// ==== 4. Insert ข้อมูลจาก DataGridView3 ไปเก็บไว้ใน MS Access ====
  205.             For Each row As DataGridViewRow In DataGridView3.Rows
  206.                 If row.IsNewRow Then Continue For
  207.                 Dim ColNames As New List(Of String)
  208.                 Dim values As New List(Of String)
  209.                 For i As Integer = 0 To DataGridView1.Columns.Count - 1
  210.                     ColNames.Add("[" & DataGridView1.Columns(i).HeaderText & "]")
  211.                     Dim val = If(IsDBNull(row.Cells(i).Value), "0", row.Cells(i).Value.ToString())
  212.                     '// เพิ่มเครื่องหมาย ' ' แค่คอลัมน์แรก (Name)
  213.                     If i = 0 Then
  214.                         values.Add("'" & val.Replace("'", "''") & "'") '// ป้องกัน single quote ในชื่อ
  215.                     Else
  216.                         '// ตรวจสอบว่าเป็นตัวเลข ถ้าไม่ใช่ ให้เป็น 0
  217.                         If Not Integer.TryParse(val, Nothing) Then val = "0"
  218.                         values.Add(val)
  219.                     End If
  220.                 Next
  221.                 Dim InsertSql As String = "INSERT INTO [" & TableName & "] (" & String.Join(",", ColNames) & ") VALUES (" & String.Join(",", values) & ")"
  222.                 Using Cmd As New OleDbCommand(InsertSql, Conn)
  223.                     Cmd.ExecuteNonQuery()
  224.                 End Using
  225.             Next
  226.             Conn.Dispose()
  227.             Conn.Close()
  228.         End Using
  229.         MessageBox.Show("บันทึกข้อมูลเรียบร้อยแล้ว: " & DbFileName, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  230.     End Sub

  231.     '// --------------------------------------------------------------------------------------
  232.     '// บันทึกข้อมูลจาก DataGridView3 ลงไปยังไฟล์ MS Access เดิม (MyData.accdb)
  233.     Private Sub btnSaveExistFile_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveExistFile.Click
  234.         Dim DbFileExist As String = "MyData.accdb"
  235.         Dim DbPath As String = MyPath(Application.StartupPath) & DbFileExist
  236.         Dim TableName As String = "Table1"
  237.         '// เชื่อมต่อฐานข้อมูล Access ที่มีอยู่
  238.         Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DbPath
  239.         Using Conn As New OleDbConnection(strConn)
  240.             Conn.Open()

  241.             '// ===== 1. ลบข้อมูลเดิมในตาราง =====
  242.             Dim DeleteSql As String = "DELETE FROM [" & TableName & "]"
  243.             Using Cmd As New OleDbCommand(DeleteSql, Conn)
  244.                 Cmd.ExecuteNonQuery()
  245.             End Using

  246.             '// ===== 2. เตรียมรายชื่อคอลัมน์ =====
  247.             Dim FieldNames As New List(Of String)
  248.             For i As Integer = 0 To DataGridView3.Columns.Count - 1
  249.                 FieldNames.Add(DataGridView3.Columns(i).Name)
  250.             Next
  251.             '// --------------------------------------------------------------------------------------
  252.             '// ใช้ Parameterized Query
  253.             '// สมมุติว่า ...
  254.             '// TableName = "Table1"
  255.             '// FieldNames = {"Name", "SCB", "KTB"}
  256.             '// Placeholders = {"?", "?", "?"}
  257.             '// ดังนั้นจะได้ ...
  258.             '// InsertSql = "INSERT INTO [Table1] ([Name],[SCB],[KTB]) VALUES (?,?,?)"
  259.             Dim Placeholders = Enumerable.Repeat("?", FieldNames.Count).ToArray()
  260.             '// คำสั่ง SQL สำหรับการ INSERT ข้อมูลแบบหลายคอลัมน์ โดยใช้ String.Format()
  261.             Dim InsertSql As String = String.Format("INSERT INTO [{0}] ({1}) VALUES ({2})", _
  262.                                                     TableName, _
  263.                                                     String.Join(",", FieldNames.Select(Function(f) "[" & f & "]").ToArray()), _
  264.                                                     String.Join(",", Placeholders))

  265.             '// ===== 3. เพิ่มข้อมูลใหม่จาก DataGridView3 เข้าไปไว้ใน MS Access =====
  266.             Using Cmd As New OleDbCommand(InsertSql, Conn)
  267.                 For Each row As DataGridViewRow In DataGridView3.Rows
  268.                     If row.IsNewRow Then Continue For
  269.                     Cmd.Parameters.Clear()
  270.                     For i As Integer = 0 To FieldNames.Count - 1
  271.                         Dim value = If(IsDBNull(row.Cells(i).Value), DBNull.Value, row.Cells(i).Value)
  272.                         Cmd.Parameters.AddWithValue("?", value)
  273.                     Next
  274.                     Cmd.ExecuteNonQuery()
  275.                 Next
  276.             End Using
  277.             Conn.Close()
  278.         End Using
  279.         MessageBox.Show("อัปเดตข้อมูลเรียบร้อยแล้วใน " & DbFileExist, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  280.     End Sub

  281.     Private Sub frmCompareDataGridView_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  282.         Me.Dispose()
  283.         GC.SuppressFinalize(Me)
  284.         Application.Exit()
  285.     End Sub

  286.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  287.         Me.Close()
  288.     End Sub

  289. #Region "FUNCTION"
  290.     Function MyPath(ByVal AppPath As String) As String
  291.         '/ Return Value
  292.         MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "").Replace("\bin\x86\release", "")
  293.         '// If not found folder then put the \ (BackSlash) at the end.
  294.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  295.     End Function
  296. #End Region

  297. #Region "DATAGRIDVIEW"
  298.     '// Initialized DataGridView.
  299.     Private Sub SetupGridView(ByRef DGV As DataGridView)
  300.         With DGV
  301.             .RowHeadersVisible = False
  302.             .AllowUserToAddRows = False
  303.             .AllowUserToDeleteRows = False
  304.             .AllowUserToResizeRows = False
  305.             .MultiSelect = False
  306.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  307.             .ReadOnly = True
  308.             '// Data rows
  309.             .Font = New Font("Tahoma", 10)
  310.             .RowTemplate.MinimumHeight = 27
  311.             .RowTemplate.Height = 27
  312.             '// Autosize Column
  313.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  314.             '// Header
  315.             With .ColumnHeadersDefaultCellStyle
  316.                 .BackColor = Color.RoyalBlue
  317.                 .ForeColor = Color.White
  318.                 .Font = New Font(DGV.Font, FontStyle.Bold)
  319.             End With
  320.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  321.             .ColumnHeadersHeight = 36
  322.             '/ Accept changes to the header's background color.
  323.             .EnableHeadersVisualStyles = False
  324.             '// Even-Odd Color of Rows.
  325.             .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
  326.             '// Even-Odd Color of Columns.
  327.             For iCol As Integer = 0 To DGV.Columns.Count - 1
  328.                 '// If any integer Mod by 2 and gets the answer is 0 so even number, 1 is an odd number.
  329.                 If iCol Mod 2 = 1 Then
  330.                     DGV.Columns(iCol).HeaderCell.Style.BackColor = Color.BlueViolet
  331.                 Else
  332.                     DGV.Columns(iCol).HeaderCell.Style.BackColor = Color.SeaGreen
  333.                 End If
  334.             Next
  335.         End With
  336.     End Sub
  337. #End Region

  338. End Class
คัดลอกไปที่คลิปบอร์ด


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

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2025-7-12 17:00 , Processed in 0.114732 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้