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

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

[VB.NET] การนำข้อมูลรายชื่อจังหวัดจาก JSON แบบออนไลน์/ออฟไลน์ มาแสดงผลในตารางกริด

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

311

กระทู้

502

โพสต์

6052

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6052





Add References ...

การนำข้อมูลรายชื่อจังหวัดจาก JSON (JavaScript Object Notation) แบบออนไลน์/ออฟไลน์ มาแสดงผลในตารางกริด ก็มีหลักการเดียวกันกับเอกสาร XML (eXtensible Markup Language) เพราะมันก็เป็นข้อมูลแบบ Text ธรรมดานั่นแหละครับ เพียงแต่จะมีการจัดทำเอกสารในรูปแบบที่แตกต่างกัน เราจึงต้องทำการดึงข้อมูลเหล่านั้นออกมาให้ได้ โดยโค้ดชุดนี้จะต้องใช้ของฟรีจาก NewtonSoft สามารถดาวน์โหลดได้จากที่นี่ ... (ในชุดโค้ดมี Newtonsoft.Json เวอร์ชั่น 13 ติดมาให้เรียบร้อยแล้วครับผม) ... หลักการคือเมื่ออ่านเอกสาร JSON เข้ามาเรียบร้อย ก็ทำการ Deserialize หรือการแยกชุดข้อมูลออกมา จากนั้นก็นำไปเก็บไว้ใน DataTable เพื่อนำมาแสดงผลอีกทีในตารางกริด ...

Thailand Geography JSON ... ทางผู้ที่ให้ข้อมูลมาบอกว่าเป็นรายชื่อจังหวัด อำเภอ ตำบล และรหัสไปรษณีย์ ที่อัพเดตจากกรมการปกครอง ปี พ.ศ.2565

กรณีของ Visual Basic .NET เวอร์ชั่น 2010 จะสามารถใช้งาน .Net Framework ได้สูงสุดที่ 4.0 ดังนั้นในงานที่ต้องติดต่อผ่านอินเทอร์เน็ต ซึ่งในปัจจุบันเว็บไซต์หรือผู้ให้บริการ API จะมีความปลอดภัยสูงขึ้น เราจึงต้องใช้คำสั่งชุดนี้เอาไว้ทุกครั้ง ...
  1.         '// Provide Security in VS2010 and .Net Framework lower than version 4.5
  2.         System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, System.Net.SecurityProtocolType)
คัดลอกไปที่คลิปบอร์ด

มาดูโค้ดกันเถอะ ...
  1. '// Special Thank ... Original JSON data.
  2. '// https://github.com/thailand-geography-data/thailand-geography-json

  3. Public Class frmJsonProvince

  4.     Private Sub frmJsonProvince_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  5.         '// Provide Security in VS2010 and .Net Framework lower than version 4.5
  6.         System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, System.Net.SecurityProtocolType)
  7.         '//
  8.         lblRecordCount.Text = ""
  9.         Me.Size = New Size(1180, 800)
  10.         Me.CenterToScreen()
  11.     End Sub

  12.     Private Sub btnOnline1_Click(sender As System.Object, e As System.EventArgs) Handles btnOnline1.Click
  13.         Call GetDataJson("https://raw.githubusercontent.com/thailand-geography-data/thailand-geography-json/main/src/geography.json")
  14.         Me.lblRecordCount.Text = "Total : " & Format(dgvData.RowCount, "#,##") & " Records."
  15.     End Sub

  16.     Private Sub btnOnline2_Click(sender As System.Object, e As System.EventArgs) Handles btnOnline2.Click
  17.         Call GetDataJsonObject("https://raw.githubusercontent.com/thailand-geography-data/thailand-geography-json/main/src/geography.json")
  18.         Me.lblRecordCount.Text = "Total : " & Format(dgvData.RowCount, "#,##") & " Records."
  19.     End Sub

  20.     Private Sub btnOffline_Click(sender As System.Object, e As System.EventArgs) Handles btnOffline.Click
  21.         Try
  22.             'Dim FileJson As String = MyPath(Application.StartupPath) & "src\provinces.json"
  23.             'Dim FileJson As String = MyPath(Application.StartupPath) & "src\districts.json"
  24.             'Dim FileJson As String = MyPath(Application.StartupPath) & "src\subdistricts.json"
  25.             Dim FileJson As String = MyPath(Application.StartupPath) & "src\geography.json"
  26.             Dim json As String = File.ReadAllText(FileJson)
  27.             Dim dt As New DataTable
  28.             dgvData.DataSource = DeserializeDataTable(json)
  29.             With dgvData.Columns
  30.                 .Remove("provinceCode")
  31.                 .Remove("districtCode")
  32.                 .Remove("subdistrictCode")
  33.             End With
  34.             Call SetupGridView()
  35.             Me.lblRecordCount.Text = "Total : " & Format(dgvData.RowCount, "#,##") & " Records."
  36.         Catch ex As Exception
  37.             MessageBox.Show("Error: " & ex.ToString())
  38.         End Try
  39.     End Sub

  40.     '// Get JSON From URL.
  41.     Private Sub GetDataJson(ByVal url As String)
  42.         Dim request As HttpWebRequest
  43.         Dim response As HttpWebResponse = Nothing
  44.         Dim reader As StreamReader
  45.         Try
  46.             request = DirectCast(WebRequest.Create(url), HttpWebRequest)
  47.             response = DirectCast(request.GetResponse(), HttpWebResponse)
  48.             reader = New StreamReader(response.GetResponseStream())
  49.             Dim s As String
  50.             s = reader.ReadToEnd
  51.             s = s.Replace("null", "0")  '// Trap Error.
  52.             Dim dt As DataTable
  53.             If Microsoft.VisualBasic.Left(s, 1) = "[" Then
  54.                 dt = DeserializeDataTable(s)
  55.             Else
  56.                 dt = DeserializeDataTable("[" & s & "]")
  57.             End If
  58.             dgvData.DataSource = dt
  59.             Call SetupGridView()
  60.         Catch ex As Exception
  61.             MessageBox.Show(ex.Message)
  62.         End Try
  63.     End Sub

  64.     '// Deserialized JSON and return DataTable.
  65.     Public Function DeserializeDataTable(json As String) As DataTable
  66.         Dim dt As DataTable = TryCast(JsonConvert.DeserializeObject(json, (GetType(DataTable))), DataTable)
  67.         Return dt
  68.     End Function

  69.     '// Get JSON by Object From URL.
  70.     Private Sub GetDataJsonObject(ByVal url As String)
  71.         Dim request As HttpWebRequest
  72.         Dim response As HttpWebResponse = Nothing
  73.         Dim reader As StreamReader
  74.         Try
  75.             request = DirectCast(WebRequest.Create(url), HttpWebRequest)
  76.             response = DirectCast(request.GetResponse(), HttpWebResponse)
  77.             reader = New StreamReader(response.GetResponseStream())
  78.             Dim s As String
  79.             s = reader.ReadToEnd.Replace("null", "0")
  80.             If Microsoft.VisualBasic.Left(s, 1) <> "[" Then
  81.                 s = "[" & s & "]"
  82.             End If
  83.             '//
  84.             Dim res() = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ItemsProvince())(s)
  85.             Dim dt As New DataTable
  86.             With dt.Columns
  87.                 .Add("ID", GetType(Integer))
  88.                 .Add("Province En", GetType(String))
  89.                 .Add("Province Th")
  90.                 .Add("Amphur En")
  91.                 .Add("Amphur Th")
  92.                 .Add("Tumbon En")
  93.                 .Add("Tumbon Th")
  94.                 .Add("Postcode")
  95.             End With
  96.             For Each province As ItemsProvince In res
  97.                 Dim dr As DataRow = dt.NewRow()
  98.                 If province IsNot Nothing Then
  99.                     dr(0) = province.id
  100.                     dr(1) = province.provinceNameEn
  101.                     dr(2) = province.provinceNameTh
  102.                     dr(3) = province.districtNameEn
  103.                     dr(4) = province.districtNameTh
  104.                     dr(5) = province.subdistrictNameEn
  105.                     dr(6) = province.subdistrictNameTh
  106.                     dr(7) = province.postalCode
  107.                 End If
  108.                 '// Add row.
  109.                 dt.Rows.Add(dr)
  110.             Next
  111.             dgvData.DataSource = dt
  112.             Call SetupGridView()
  113.         Catch ex As Exception
  114.             MessageBox.Show(ex.Message)
  115.         End Try
  116.     End Sub

  117.     '// Initialized DataGridView.
  118.     Private Sub SetupGridView()
  119.         With dgvData
  120.             .RowHeadersVisible = True
  121.             .AllowUserToAddRows = False
  122.             .AllowUserToDeleteRows = False
  123.             .AllowUserToResizeRows = False
  124.             .MultiSelect = False
  125.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  126.             .ReadOnly = True
  127.             '// Data rows
  128.             .Font = New Font("Tahoma", 11)
  129.             .RowTemplate.MinimumHeight = 27
  130.             .RowTemplate.Height = 27
  131.             '// Column Header
  132.             .ColumnHeadersHeight = 30
  133.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  134.             '// Autosize Column
  135.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  136.             '// Header
  137.             With .ColumnHeadersDefaultCellStyle
  138.                 .BackColor = Color.SeaGreen
  139.                 .ForeColor = Color.White
  140.                 .Font = New Font(dgvData.Font, FontStyle.Bold)
  141.             End With
  142.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  143.             .ColumnHeadersHeight = 36
  144.             '/ Accept changes to the header's background color.
  145.             .EnableHeadersVisualStyles = False
  146.             '// Even-Odd Color of Rows.
  147.             .AlternatingRowsDefaultCellStyle.BackColor = Color.BlanchedAlmond
  148.             '// Even-Odd Color of Columns.
  149.             For iCol As Integer = 0 To dgvData.Columns.Count - 1
  150.                 '// If any integer Mod by 2 and gets the answer is 0 so even number, 1 is an odd number.
  151.                 If iCol Mod 2 = 1 Then
  152.                     dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.BlueViolet
  153.                 Else
  154.                     dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.SeaGreen
  155.                 End If
  156.             Next
  157.         End With
  158.     End Sub

  159.     '// Show row number in row header of a DataGridView.
  160.     Private Sub dgvData_RowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs) Handles dgvData.RowPostPaint
  161.         Dim grid As DataGridView = CType(sender, DataGridView)
  162.         Dim rowIdx As String = (e.RowIndex + 1).ToString()
  163.         Dim rowFont As New System.Drawing.Font("Tahoma", 10.0!, _
  164.             System.Drawing.FontStyle.Regular, _
  165.             System.Drawing.GraphicsUnit.Point, CType(0, Byte))

  166.         Dim centerFormat = New StringFormat()
  167.         centerFormat.Alignment = StringAlignment.Center
  168.         centerFormat.LineAlignment = StringAlignment.Center

  169.         Dim headerBounds As Rectangle = New Rectangle( _
  170.                                         e.RowBounds.Left - 10, e.RowBounds.Top, _
  171.                                         grid.RowHeadersWidth + 20, e.RowBounds.Height)
  172.         e.Graphics.DrawString(rowIdx, rowFont, SystemBrushes.ControlText, _
  173.                               headerBounds, centerFormat)
  174.     End Sub

  175.     Private Sub frmJsonProvince_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  176.         Me.Dispose()
  177.         GC.SuppressFinalize(Me)
  178.         Application.Exit()
  179.     End Sub

  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(ByVal 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 Class

  192. Public Class ItemsProvince
  193.     Public Property id As String
  194.     Public Property provinceNameEn As String
  195.     Public Property provinceNameTh As String
  196.     Public Property districtNameEn As String
  197.     Public Property districtNameTh As String
  198.     Public Property subdistrictNameEn As String
  199.     Public Property subdistrictNameTh As String
  200.     Public Property postalCode As Integer
  201. End Class
คัดลอกไปที่คลิปบอร์ด

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



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

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

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

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

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

GMT+7, 2024-4-27 05:55 , Processed in 0.365267 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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