0

I have been looking for the specified code all day long, browsing through the MSDN libraries from microsoft, but I wasn't able to find or come up with a solution:

Question: How can I add a string to an existing array?

I have been trying this

Dim Items() As String
Items = ListBox1.Items.Cast(Of String).ToArray
Array.Reverse(Items)
Me.ListBox1.Items.Clear()
Me.ListBox1.DataSource = Items

**Items.add("Add This to my array")**

But this doesn't work unfortunately.

My code is loading a populated listbox into an array (reverses the entries, and then cleans the listbox before populating it with the array).

How can I add to this array now?

5
  • 2
    If it was a List(Of String) you could do that. Commented Feb 22, 2016 at 18:20
  • how would I need to define it..I was having troubles for instance with this line Dim Items() As String = ListBox1.Items.Cast(Of String).ToArray How would it has to look to define Items() as a List? Commented Feb 22, 2016 at 18:29
  • 2
    Try Redim preserve Items(Items.Count) 'Adds a new element to end of array. Items(Items.Count-1) = "Add this to my array" Commented Feb 22, 2016 at 18:29
  • In most all cases, a List(of String) should be preferred to an array. They are easier, more flexible than arrays, yet used/referenced almost identically. Commented Feb 22, 2016 at 18:58
  • ...If you will be adding other strings to the collection, a BindingList<T> would be a better choice. Commented Feb 22, 2016 at 19:08

1 Answer 1

1

Try this.....

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim Items As List(Of String)
    Items = ListBox1.Items.Cast(Of String).ToList

    Items.Reverse()

    Items.Add("Add This to my array")

    Me.ListBox1.Items.Clear()
    Me.ListBox1.DataSource = Items
End Sub
End Class

almost identical code (slightly rearranged), using a List instead of an array

Sign up to request clarification or add additional context in comments.

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.