user3639140
user3639140

Reputation: 3

Making an array of string in VB

I'm trying to make an array of string, but can't get it to run correctly. Here is what I have.

Public Class Form1
Dim wordArray() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'increase the size of string array by one, by setting the new upperBound at the current Length

    'use Preserve so that string currently in the array are not overwritten with Nothing

    ReDim Preserve wordArray(wordArray.Length)

    'use an TextBox to get the name of the new string from the user

    'assign this name (which is a String) to the last element of the string array

    wordArray(wordArray.GetUpperBound(0)) = TextBox2.Text
End Sub
End Class

Any help will be appreciated, thank you.

Upvotes: 0

Views: 262

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

You should use Collections here like List(Of String), it grows as the number of element grows. No need to maintain size yourself. Also the problem might at your end is, when you ReDim try to increase your array size.

ReDim Preserve wordArray(wordArray.Length + 1)

Upvotes: 0

Bla...
Bla...

Reputation: 7288

For Fixed-size array:

Dim strCDRack(0 to 2) As String 

strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"

For Dynamic array:

Dim strCDRack() As String 

ReDim strCDRack(0 to 2) As String 

strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed"

For expanding the Dynamic array:

Dim strCDRack() As String 

ReDim strCDRack(0 to 2) As String 

strCDRack(0) = "Deftones"
strCDRack(1) = "Tool"
strCDRack(2) = "Disturbed" 

ReDim Preserve strCDRack(0 to 3) As String 

strCDRack(3) = "Charlotte Church"

For more info about VB arrays checkout this link..

Upvotes: 1

andypopa
andypopa

Reputation: 536

Use a list!

Dim StringArray As New List(Of [String])()

And in the click handler:

StringArray.Add(TextBox1.Text)

Upvotes: 0

OneFineDay
OneFineDay

Reputation: 9024

How about a List(Of String)? No ReDim required here.

Private wordList As New List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  wordList.Add(textbox2.Text)
End Sub

Upvotes: 4

Related Questions