failure
failure

Reputation: 235

ReDim doesn't reduce array

If this is a duplicate, sorry, I did search first, though.

Visual Basic 2013, the assignment is specific to arrays so I can't use lists. Add items to array and remove them, ReDim will enlarge it but not reduce it. The code:

    Private Strings(-1) As String

   Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
    ReDim Preserve Strings(Strings.Length)
    Strings(Strings.Length - 1) = TextBox.Text
    ShowStrings()
    TextBox.Text = ""
    Label.Text = Strings.Length
End Sub

Private Sub RemoveButton_Click(sender As Object, e As EventArgs) Handles RemoveButton.Click
    Dim length As Integer = Strings.Length - 1
    Dim what As Integer = ListBox.SelectedIndex

    Do While what < length
        Strings(what) = Strings(what + 1)
        what = what + 1
    Loop
    ReDim Preserve Strings(length)
    Label.Text = Strings.Length
    ShowStrings()
End Sub

As I said, the ReDim in AddButton successfully enlarges the array, the in RemoveButton's ReDim does not shrink the array. I tried it without the Preserve, same problem, so that's not it.

Thanks for any ideas. Again, I realize this isn't the optimal solution (heck, if this wasn't for a homework about arrays, I'd just use ListBox's methods), so let's stay within the parameters, please.

Upvotes: 0

Views: 416

Answers (1)

Josh
Josh

Reputation: 1093

Change

ReDim Preserve Strings(length)

to

ReDim Preserve Strings(length - 1)

Upvotes: 1

Related Questions