thongkorn โพสต์ 2024-1-10 12:25:26

[VB.NET] ทำความเข้าใจและใช้งาน List (Of Object)

http://www.g2gsoft.com/webboard/images/VBNet/listofobject.png


สืบเนื่องจากการที่แอดมินได้แจกโค้ด VB.NET กับการอ่านเขียนข้อมูลลงใน Google Sheets ซึ่งจะมองเห็นชีตเป็นเหมือนแผ่นข้อมูล หรือตารางข้อมูลนั่นเอง แต่การเข้าถึงชีต ไม่สามารถกระทำได้เหมือนทำกับฐานข้อมูล เราจึงมองชีตเป็นแบบ Array หรือ List ในการเข้าถึงข้อมูลได้จึงต้องทำแบบ Sequential หรือแบบเรียงลำดับ ด้วยการใช้ Index หรือแถวลำดับนั่นเอง จึงต้องนำ List (Of Object) เข้ามาช่วย ...

List (Of Object) คือรูปแบบ List ใน Visual Basic .NET เพื่อใช้เก็บข้อมูลในรูปแบบของ Object ซึ่งจะไม่ระบุประเภทข้อมูลเอาไว้ล่วงหน้า (Non-Generic) ซึ่งทำให้สามารถเก็บข้อมูลประเภทต่างๆได้ใน List เดียว ข้อมูลที่ว่าก็คือ ข้อความ, ตัวเลขจำนวนเต็มหรือทศนิยม, วันเดือนปี, บูลีน หรือแม้แต่ Class ...

มาดูโค้ดฉบับเต็มกันเถอะ ...
Public Class frmListOfObject

    '// Example of a class used in a list.
    Class CustomClass
      Public Overrides Function ToString() As String
            Return "I'm a custom class!"
      End Function
    End Class

    ' / --------------------------------------------------------------------------------
    Private Sub btnSampleOne_Click(sender As System.Object, e As System.EventArgs) Handles btnSampleOne.Click
      TextBox1.Clear()
      TextBox2.Clear()
      'Dim ListObject As List(Of Object) = New List(Of Object)()
      Dim ListObject As New List(Of Object)
      '// เพิ่มข้อมูลลงในลิสต์
      ListObject.Add("Hello, World!")
      ListObject.Add(42)
      ListObject.Add(3.14)
      ListObject.Add(DateTime.Now)
      ListObject.Add(True)
      ListObject.Add(New CustomClass())
      '// Use String.Join to combine the items in a List into a single message.
      TextBox1.Text = String.Join(vbNewLine, ListObject)
      TextBox1.Text = TextBox1.Text & vbNewLine & "Total : " & ListObject.Count
    End Sub

    ' / --------------------------------------------------------------------------------
    Private Sub btnSampleTwo_Click(sender As System.Object, e As System.EventArgs) Handles btnSampleTwo.Click
      TextBox1.Clear()
      TextBox2.Clear()
      '// Create a List(Of Object) with two columns.
      Dim ListObject As New List(Of Object)
      '// Add data to the two-column list.
      ListObject.Add(New List(Of Object) From {"Name", "Age"})
      ListObject.Add(New List(Of Object) From {"John", 30})
      ListObject.Add(New List(Of Object) From {"Alice", 25})
      ListObject.Add(New List(Of Object) From {"Bob", 35})
      '// Looping data in a list.
      For Each row As List(Of Object) In ListObject
            TextBox1.Text = TextBox1.Text & row(0) & vbTab & row(1) & vbNewLine
      Next
      TextBox1.Text = TextBox1.Text & vbNewLine & "Total : " & ListObject.Count
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / ADD
    ' / --------------------------------------------------------------------------------
    Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
      TextBox1.Clear()
      TextBox2.Clear()
      '// Create a List(Of Object) with two columns.
      Dim ListObject As New List(Of Object)
      '// Add members to the list.
      ListObject.Add(New List(Of Object) From {"Name", "Age"})
      Dim row1 As New List(Of Object) From {"John", 25}
      Dim row2 As New List(Of Object) From {"Alice", 30}
      Dim row3 As New List(Of Object) From {"Bob", 35}
      ListObject.Add(row1)
      ListObject.Add(row2)
      ListObject.Add(row3)
      '// Display members.
      Call DisplayList(ListObject)
      '// Input new data to List.
      Dim Name As String = InputBox("Enter your name:", "User Input", "Name")
      Dim Age As String = InputBox("Enter your age:", "User Input", "30")
      Dim NewRow As New List(Of Object) From {Name, Age}
      '// Add a new row.
      ListObject.Add(NewRow)
      '// Show update data in the list.
      TextBox2.Text = TextBox1.Text & Name & vbTab & Age & vbNewLine
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / EDIT
    ' / --------------------------------------------------------------------------------
    Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
      TextBox1.Clear()
      TextBox2.Clear()
      '// Create a List(Of Object) with two columns.
      Dim ListObject As New List(Of Object)
      '// Add data to the two-column list.
      With ListObject
            .Add(New List(Of Object) From {"Name", "Age"})
            .Add(New List(Of Object) From {"John", 30})
            .Add(New List(Of Object) From {"Alice", 25})
            .Add(New List(Of Object) From {"Bob", 35})
      End With
      '// Show data in list.
      Call DisplayList(ListObject)
      '// Select the row index you want to edit.
      Dim RowNum As String = InputBox("Enter number of row to edit:", "User Input", "0")
      If String.IsNullOrEmpty(RowNum) Then Return
      '// Check if the row number is within the valid range of indices in the list.
      If RowNum >= 0 AndAlso RowNum < ListObject.Count Then
            '// Get the data for row to edit.
            Dim RowEdit As List(Of Object) = ListObject(RowNum)
            '// Prompt the user to edit the values.
            Dim NewName As String = InputBox("Enter new name :", "Edit Name", RowEdit(0).ToString())
            Dim NewAge As String = InputBox("Enter new age :", "Edit Age", RowEdit(1).ToString())
            If String.IsNullOrEmpty(NewName) OrElse String.IsNullOrEmpty(NewAge) Then
                MessageBox.Show("User canceled or entered invalid input.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Return
            End If
            '// Update the values in the row.
            RowEdit(0) = NewName
            RowEdit(1) = NewAge
            '// Display update data list into TextBox2.
            For Each row As List(Of Object) In ListObject
                TextBox2.Text = TextBox2.Text & row(0) & vbTab & row(1) & vbNewLine
            Next
      Else
            MessageBox.Show("The specified row does not exist in the list.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
      End If
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / REMOVE
    ' / --------------------------------------------------------------------------------
    Private Sub btnRemove_Click(sender As System.Object, e As System.EventArgs) Handles btnRemove.Click
      TextBox1.Clear()
      TextBox2.Clear()
      '// Create a List(Of Object) with two columns.
      Dim ListObject As New List(Of Object)
      ListObject.Add(New List(Of Object) From {"Name", "Age"})
      Dim row1 As New List(Of Object) From {"John", 25}
      Dim row2 As New List(Of Object) From {"Alice", 30}
      Dim row3 As New List(Of Object) From {"Bob", 35}
      '// Add members to the list.
      ListObject.Add(row1)
      ListObject.Add(row2)
      ListObject.Add(row3)
      Call DisplayList(ListObject)
      '// Select the row index you want to remove.
      Dim RowNum As String = InputBox("Enter number of row to remove:", "User Input", "0")
      If String.IsNullOrEmpty(RowNum) Then Return
      '// Check if the row number is within the valid range of indices in the list.
      If RowNum >= 0 AndAlso RowNum < ListObject.Count Then
            ListObject.RemoveAt(RowNum) ' Remove the row at index.
            '// Display update data list into TextBox2.
            For Each row As List(Of Object) In ListObject
                TextBox2.Text = TextBox2.Text & row(0) & vbTab & row(1) & vbNewLine
            Next
      Else
            MessageBox.Show("The specified row does not exist in the list.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
      End If
    End Sub

    ' / --------------------------------------------------------------------------------
    Private Sub DisplayList(List As List(Of Object))
      For Each row As List(Of Object) In List
            TextBox1.Text = TextBox1.Text & row(0) & vbTab & row(1) & vbNewLine
      Next
    End Sub

    Private Sub frmListOfObject_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      Me.Dispose()
      GC.SuppressFinalize(Me)
      End
    End Sub
End Class

ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] ทำความเข้าใจและใช้งาน List (Of Object)