vb.netlistdirectcast

Use directcast to call a list


I'm looking for a way to avoid using select case to access a specific list; I'll have about 90 lists on a module, and depending on a record selected on a listbox (manually populated with the name of most of the tables of my database, but not all of them) I need to read the items of the list. So I have something like this:

Public RelevantTables_Table001 As List(Of Table001) = New List(Of Table001)
Public RelevantTables_Table002 As List(Of Table002) = New List(Of Table002)
'...
Public RelevantTables_Table999 As List(Of Table999) = New List(Of Table999)

Class Table001
'code for populating RelevantTables_Table001
End Class

Class Table002
'code for populating RelevantTables_Table002
End Class

Class Table999
'code for populating RelevantTables_Table999
End Class

And now I need to read the relevant list, depending on an item picked on a listbox. For example if someone picks Table042 I need to read the items of the list RelevantTables_Table042.

I'm trying to use DirectCast for this, but I can't figure out how to do it.


Solution

  • Class:

    Public Class Table
      Public Tablename As String
      Public Collection As New List(Of String)
      Public Overrides Function ToString() As String
        Return Me.TableName
      End Function
    End Class
    

    Create new List:

    Private RelevantTable_Table001 As New Table
    RelevantTable_Table001.Tablename = "Table001"
    RelevantTable_Table001.Collection.Add("stuff")
    ...
    'add the class and it will display the TableName since we 
    'overrided the ToString function 
    lsb.Items.Add(RelevantTable_Table001)
    'class objects can be stored in the listbox as an object
    

    Get the List object from the SelectedItem property.

    Private Sub lsb_SelectedIndexChanged(sender As Object, e As EventArgs)
      Dim tableList = TryCast(DirectCast(sender, ListBox).SelectedItem, Table)
      If tableList IsNot Nothing Then
        'tableList is the reference to the table object you seek.
      End If
    End Sub
    

    To make a list of several objects(columns in a DGV) use a custom class:

    Public Class MyCustomClass
      Public Property Prop1 As String
      Public Property Prop2 As String
      Public Property Prop3 As String
    End Class
    

    Then your Table.Collection would be a List(Of MyCustomClass) instead of a string, this will give you 3 items per collection items - which is a table. Does that fit your needs?