Wednesday, May 9, 2012

Sample Code Using ListBox with VB.NET


Public Class MyListBox
    '1. Copy All Items From ListBOx1 to ListBox2
    Public Shared Sub CopyAllItems(ByRef ListBoxName1 As ListBox, ByRef ListBoxName2 As ListBox)
        If ListBoxName1.Items.Count > 0 Then
            For i As UShort = 0 To ListBoxName1.Items.Count - 1
                ListBoxName2.Items.Add(ListBoxName1.Items.Item(i))
            Next
        End If
    End Sub

    '2. Copy Selcted Items From ListBOx1 to ListBox2
    Public Shared Sub CopySelectedItems(ByRef ListBoxName1 As ListBox, ByRef ListBoxName2 As ListBox)
        If ListBoxName1.SelectedItems.Count > 0 Then
            For i As UShort = 0 To ListBoxName1.SelectedItems.Count - 1
                ListBoxName2.Items.Add(ListBoxName1.SelectedItems.Item(i))
            Next
        End If
    End Sub

    '3. Delete All Items in ListBox
    Public Shared Sub DeleteAllItems(ByRef ListBoxName As ListBox)
        ListBoxName.Items.Clear()
    End Sub

    '4. Delete All SelectedItems
    Public Shared Sub DeleteSelectedItems(ByRef ListBoxName As ListBox)
        Do Until ListBoxName.SelectedIndices.Count = 0
            ListBoxName.Items.RemoveAt(ListBoxName.SelectedIndex)
        Loop
    End Sub

    '5. Back Up ListBox to Object Collection
    Public Shared Sub Backup(ByRef ListBoxName As ListBox, ByRef ObjCol As Collection)
        'Clear the old value in ObjCol Collection.
        ObjCol.Clear()
        'Copy all items in Items collection of ListBoxName to ObjCol
        If ListBoxName.Items.Count > 0 Then
            For i As UShort = 0 To ListBoxName.Items.Count - 1
                ObjCol.Add(ListBoxName.Items.Item(i))
            Next
        End If
    End Sub

    '6. Restore ListBox from Object Collection
    Public Shared Function Restore(ByRef ListBoxName As ListBox, ByRef ObjCol As Collection) As Boolean
        If ObjCol IsNot Nothing Then
            'Delete All Item in ListBox
            DeleteAllItems(ListBoxName)
            'Restore all items in ListBoxName from ObjCol
            If ObjCol.Count > 0 Then
                For i As UShort = 1 To ObjCol.Count
                    ListBoxName.Items.Add(ObjCol.Item(i))
                Next
            End If
            Return True
        Else
            Return False
        End If
    End Function
End Class

No comments:

Post a Comment