Question

In my code I basically read a textbox and put each line into a list (Of String) Dim "testblock" in code below

From there I create another list (of string) and split each line whenever a space is found. Dim "block" in code below

Now I want to be able to access that list from anywhere in the project.

How do I go about sharing a List of(String) between Private Sub such as form buttons?

Private Sub PhaseCodeBTN_Click(sender As Object, e As EventArgs) Handles PhaseCodeBTN.Click
    Dim testblock As New List(Of String)
    Dim lines As String() = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    Dim block As New List(Of String)

    For Each l As String In lines
        testblock.Add(l)
        Dim words As String() = BlockCodeBox.Text.Split(" ")
        For Each splitword As String In words
            block.Add(splitword)
        Next
    Next
    BlockCodeBox.Text = testblock(BlockNumBox.Text)
    WordCmdBox.Text = block(WordNumBox.Text)

End Sub

Private Sub PhaseBlackBTN_Click(sender As Object, e As EventArgs) Handles PhaseBlackBTN.Click

    WordCmdBox.Text = block(WordNumBox.Text)
End Sub
Was it helpful?

Solution

Create a Public Shared Class with your List(Of String) there to use it anywhere in the project:

Public Shared Class DataHolder

    Private _block As New List(Of String)

    Public Property Block As List(Of String)
    Get
        Return _block
    End Get        
    Set
        _block = value
    End Set
    End Property

End Class

Example:

Either simply use DataHolder.Block.Add(splitword) OR following steps:

  1. Declare a class variable block to use it in entire class:

    Private block As List(Of String)
    
  2. Initialize it in some suitable function / event-handler like Form_Load:

    block = DataHolder.Block 
    
  3. Do the operation:

    block.Add(splitword)
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top