0

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?

1
  • 1
    In Sub button1 you have declared another array named "array1". It is not the same variable as the "array1" which is declared in the class. Please google for "vb.net variable scope" to learn more. Commented Dec 17, 2020 at 20:40

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.