Lisa99
Lisa99

Reputation: 3

How to access a form array from different buttons in vb.net?

I'm learning vb.net and have a problem. Short version of code.

I have structure like this:

public class form234

public array1() as string

public sub button1

    Dim i As Integer
            Dim array1(Len(text)) As String
            For i = 1 To 3
                array1(i) = "x"
                TextBox2.Text = TextBox2.Text & array1(i) & " "
            Next

When I put a msgbox here I get the content of my array

......

public sub button2

When I put a msgbox here I get error and array1 is "nothing"

...........

Why? How can I use my array value of sub button1 in sub button 2 as well?

Upvotes: 0

Views: 105

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

I'd write that as:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ReDim array1(Text.Length)
    For i As Integer = 0 To array1.Length - 1
        array1(i) = "x"
        TextBox2.Text = String.Join(" ", array1)
    Next
End Sub

Upvotes: 1

B.S.
B.S.

Reputation: 678

your problem is that you declared a second time your array1 in public sub button1.

if you want really to use the one that you declared public, you have to give him a size, the thing that you can do in his first declaration.

Else an alternative solution can be :

    Dim i As Integer
    
    Array.Resize(array1, Len(Text))
    For i = 1 To 3
        array1(i) = "x"
        TextBox2.Text = TextBox2.Text & array1(i) & " "
    Next

Upvotes: 0

Related Questions