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

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

[VB.NET] โค้ดตัวอย่างของการนำชุดข้อมูลหลายชุดทั้ง Table หรือ Query ใส่ไว้ใน DataSet ตัวเดียว

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

311

กระทู้

502

โพสต์

6060

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6060




โค้ดตัวอย่างซึ่งแอดมินคิดว่าน่าจะเพิ่มความเข้าใจได้ดีขึ้นระหว่างคำว่า DataSet กับ DataTable เพราะว่าเราสามารถนำชุดข้อมูลหลายชุดทั้ง Table หรือ Query ใส่ไว้ใน DataSet เพียงตัวเดียวได้ ส่วน DataTable จะใส่ได้เพียงทีละ 1 Table หรือ 1 Query เท่านั้น ...


มาดูโค้ดฉบับเต็มกันเถอะ ...
  1. Public Class frmMultipleDataSet
  2.     Private Conn As New OleDbConnection
  3.     '// Data Path
  4.     Private strPathData As String = MyPath(Application.StartupPath) & "Data"
  5.     Dim MyDataSet As New DataSet()

  6.     ' / ------------------------------------------------------------------------------------
  7.     ' / S T A R T ... H E R E
  8.     ' / ------------------------------------------------------------------------------------
  9.     Private Sub frmMultipleDataSet_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  10.         Call ConnectDataBase()  '// Connect Northwind.accdb DataBase.
  11.         Call InitialDataGridView()  '// Initialized DataGridView one time for DataSet.
  12.         '//
  13.         Dim Tables(4) As String '// (Indexs 0 - 4 of 5 Tables)
  14.         Tables(0) = "customers" : Tables(1) = "employees" : Tables(2) = "products" : Tables(3) = "suppliers" : Tables(4) = "orders"
  15.         MyDataSet = GetDataSet(Tables)
  16.         '// Tables in DataSet.
  17.         With cmbDataSet
  18.             .Items.Add("Customers")
  19.             .Items.Add("Employees")
  20.             .Items.Add("Products")
  21.             .Items.Add("Suppliers")
  22.             .Items.Add("Orders")
  23.             .Items.Add("Sample Query")
  24.         End With
  25.         cmbDataSet.SelectedIndex = 0
  26.         '// DataTable.
  27.         With cmbDataTable
  28.             .Items.Add("Customers")
  29.             .Items.Add("Employees")
  30.             .Items.Add("Products")
  31.             .Items.Add("Suppliers")
  32.             .Items.Add("Orders")
  33.             .Items.Add("Sample Query")
  34.         End With
  35.         cmbDataTable.SelectedIndex = 0
  36.     End Sub

  37.     ' / ------------------------------------------------------------------------------------
  38.     '// Multiple Tables/Query in DataSet.
  39.     ' / ------------------------------------------------------------------------------------
  40.     Private Function GetDataSet(ByRef Tables() As String) As System.Data.DataSet
  41.         If Conn.State = ConnectionState.Closed Then Conn.Open()
  42.         Dim Cmd As New OleDbCommand()
  43.         Cmd.Connection = Conn
  44.         Cmd.CommandType = System.Data.CommandType.Text
  45.         Dim DA As OleDbDataAdapter = New OleDbDataAdapter(Cmd)
  46.         Dim DS As DataSet = New DataSet()
  47.         '// Fill data from many tables or queries into DataSet object.
  48.         For intCount As Byte = 0 To Tables.GetUpperBound(0)
  49.             Cmd.CommandText = "SELECT * FROM " & Tables(intCount)
  50.             DA.Fill(DS, Tables(intCount))
  51.         Next
  52.         '// Add new sample query. (6 Tables in 1 DataSet)
  53.         Dim sql As String = _
  54.             " SELECT Orders.OrderID, Customers.CustomerID, Customers.CompanyName, Orders.OrderDate, " & _
  55.             " Products.ProductName, [Order Details].Quantity, Products.UnitPrice " & _
  56.             " FROM Products INNER JOIN (Customers INNER JOIN (Orders INNER JOIN [Order Details] ON " & _
  57.             " Orders.OrderID = [Order Details].OrderID) ON Customers.CustomerID = Orders.CustomerID) ON " & _
  58.             " Products.ProductID = [Order Details].ProductID"
  59.         Cmd.CommandText = sql
  60.         DA.Fill(DS, "SampleQuery")  '// Also give the new data table a name.
  61.         '//
  62.         Conn.Close()
  63.         Return DS
  64.     End Function

  65.     ' / ------------------------------------------------------------------------------------
  66.     ' / Select Table/Query in DataSet.
  67.     ' / ------------------------------------------------------------------------------------
  68.     Private Sub cmbDataSet_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbDataSet.SelectedIndexChanged
  69.         Select Case cmbDataSet.SelectedIndex
  70.             Case 0
  71.                 dgvData.DataSource = MyDataSet.Tables("customers").DefaultView
  72.             Case 1
  73.                 dgvData.DataSource = MyDataSet.Tables("employees").DefaultView
  74.             Case 2
  75.                 dgvData.DataSource = MyDataSet.Tables("products").DefaultView
  76.             Case 3
  77.                 dgvData.DataSource = MyDataSet.Tables("suppliers").DefaultView
  78.             Case 4
  79.                 dgvData.DataSource = MyDataSet.Tables("orders").DefaultView
  80.             Case 5
  81.                 dgvData.DataSource = MyDataSet.Tables("SampleQuery").DefaultView
  82.         End Select
  83.     End Sub

  84.     ' / ------------------------------------------------------------------------------------
  85.     ' / Sample for DataSet to DataTable.
  86.     ' / ------------------------------------------------------------------------------------
  87.     Private Sub btnDataSetToDataTable_Click(sender As System.Object, e As System.EventArgs) Handles btnDataSetToDataTable.Click
  88.         '// DataTable can contain only 1 table.
  89.         Dim DT As New DataTable
  90.         Select Case cmbDataTable.SelectedIndex
  91.             Case 0
  92.                 DT = MyDataSet.Tables(0)
  93.                 dgvData.DataSource = DT
  94.             Case 1
  95.                 DT = MyDataSet.Tables(1)
  96.                 dgvData.DataSource = DT
  97.             Case 2
  98.                 DT = MyDataSet.Tables(2)
  99.                 dgvData.DataSource = DT
  100.             Case 3
  101.                 DT = MyDataSet.Tables(3)
  102.                 dgvData.DataSource = DT
  103.             Case 4
  104.                 DT = MyDataSet.Tables(4)
  105.                 dgvData.DataSource = DT

  106.                 '// Query.
  107.             Case 5
  108.                 'DT = MyDataSet.Tables(5)
  109.                 '// Or use the name of Table.
  110.                 DT = MyDataSet.Tables("SampleQuery")
  111.                 '//
  112.                 If dgvData.Rows.Count > 0 Then dgvData.DataSource = Nothing
  113.                 '// If there is a column named Total, delete it from the DataTable.
  114.                 If DT.Columns.Contains("Total") Then DT.Columns.Remove("Total")
  115.                 '// Add a new column to calculate the sum of the Quantity X UnitPrice.
  116.                 DT.Columns.Add("Total", GetType(Double))
  117.                 DT.Columns("Total").Expression = "[Quantity] * [UnitPrice]"
  118.                 '// An example of how to customize the display of DataGridView with DataTable.
  119.                 dgvData.DataSource = DT
  120.                 With dgvData
  121.                     .Columns(0).HeaderText = "Order ID"
  122.                     .Columns(1).HeaderText = "Customer ID"
  123.                     .Columns(2).HeaderText = "Company Name"
  124.                     .Columns(3).HeaderText = "Order Date"
  125.                     .Columns(4).HeaderText = "Product Name"
  126.                     .Columns(5).HeaderText = "Quantity"
  127.                     With .Columns(6)
  128.                         .HeaderText = "Unit Price"
  129.                         .DefaultCellStyle.Format = "0.00"
  130.                         .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
  131.                         .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
  132.                     End With
  133.                     '// Columns(7) and Columns("Total") is the same.
  134.                     .Columns(7).HeaderText = "Total"
  135.                     .Columns("Total").DefaultCellStyle.Format = "N2"
  136.                     .Columns(7).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
  137.                     .Columns("Total").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
  138.                 End With
  139.         End Select
  140.     End Sub

  141.     ' / ------------------------------------------------------------------------------------
  142.     Sub InitialDataGridView()
  143.         With dgvData
  144.             .RowHeadersVisible = False
  145.             .AllowUserToAddRows = False
  146.             .AllowUserToDeleteRows = False
  147.             .AllowUserToResizeRows = False
  148.             .MultiSelect = False
  149.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  150.             .ReadOnly = True
  151.             ' Autosize Column Mode.
  152.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  153.             .RowTemplate.DefaultCellStyle.Font = New Font("Tahoma", 11, FontStyle.Regular)
  154.             .RowTemplate.Height = 32
  155.             '// Set ColumnHeadersHeightSizeMode before adjusting row heights.
  156.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
  157.             .ColumnHeadersHeight = 28
  158.             '// Set EnableHeadersVisualStyles = False to accept background color changes.
  159.             .EnableHeadersVisualStyles = False
  160.             '// Even-Odd Color
  161.             .AlternatingRowsDefaultCellStyle.BackColor = Color.LightYellow ' .AliceBlue
  162.             '// Example of adjusting Header Style.
  163.             With .ColumnHeadersDefaultCellStyle
  164.                 .BackColor = Color.Orange
  165.                 .ForeColor = Color.Black
  166.                 .Font = New Font("Tahoma", 11, FontStyle.Bold)
  167.             End With
  168.         End With
  169.     End Sub

  170.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  171.         Me.Close()
  172.     End Sub

  173.     Private Sub frmMultipleDataSet_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  174.         Conn.Close()
  175.         Me.Dispose()
  176.         GC.SuppressFinalize(Me)
  177.         Application.Exit()
  178.     End Sub

  179. #Region "FUNCTION"
  180.     ' / --------------------------------------------------------------------------------
  181.     ' / Get my project path
  182.     ' / AppPath = C:\My Project\bin\debug
  183.     ' / Replace "\bin\debug" with ""
  184.     ' / Return : C:\My Project\
  185.     Function MyPath(AppPath As String) As String
  186.         '/ Return Value
  187.         MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  188.         '// If not found folder then put the \ (BackSlash) at the end.
  189.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  190.     End Function
  191. #End Region

  192. #Region "CONNECTDATABASE"
  193.     Public Function ConnectDataBase() As Boolean
  194.         Dim strConn As String = _
  195.                 "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " & strPathData & "Northwind.accdb"
  196.         Try
  197.             Conn = New OleDb.OleDbConnection(strConn)
  198.             '// Create Connection
  199.             Conn.ConnectionString = strConn
  200.             Conn.Open()
  201.             '// Return
  202.             Return True
  203.         Catch ex As Exception
  204.             MessageBox.Show(ex.Message)
  205.             Conn = Nothing
  206.             Return False
  207.             'End
  208.         End Try
  209.     End Function

  210. #End Region
  211. End Class
คัดลอกไปที่คลิปบอร์ด


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

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

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

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

0

กระทู้

3

โพสต์

36

เครดิต

Newbie

Rank: 1

เครดิต
36
โพสต์ 2023-10-31 11:55:51 | ดูโพสต์ทั้งหมด

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

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

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

GMT+7, 2024-4-30 01:25 , Processed in 0.284467 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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