-2

I have a custom control object called cc1. I store cc1 like this Public cc1List As New List(Of cc1) and add stuff to it, works like a charm.

Now i want to remove some item inside it, with a known index, so i create Dim cc1ListTemp As New List(Of cc1), loop through the whole index of cc1, and append all items excluding the removed index through this Code: cc1ListTemp.Add(cc1List(i)) but it keeps on throwing an OutOfRangeException, beginning with the first loop (i = 0) all the way up.

But i know for sure that cc1List(i) where i = 0 to 5 is fully populated, and checked even in runtime before triggering the exception (i can fully access/edit/call cc1List(0)).

Do i need to append in a different way? If needed i can provide more code.

Edit0:

        Dim cc1ListTemp As New List(Of cc1)
        For i = 0 To CWBListMaxIndex
            If Not i = IndexToRemove Then
                cc1ListTemp.Add(cc1List(i))
            End If
        Next
        cc1List = cc1ListTemp

Adding works fine, mixed add/append.

cc1List.Append(cc1TempObject)
cc1List.Add(cc1TempObject)

Edit1: reproduced it with Textboxes replacing cc1 inside a new project.

  • I don't see an issue with what you've shown so far. – Craig Sep 30 '21 at 18:21
  • 2
    Post the full code of the issue. – LarsTech Sep 30 '21 at 18:22
  • 1
    `CWBListMaxIndex` is maybe out of sync? Try `cc1List.Count - 1` instead. – LarsTech Sep 30 '21 at 18:37
  • @LarsTech CWBListMaxIndex is defined publicly, and incremented by 1 each time the list is added/appended, guaranteed. Also the error is thrown on first loop, while i = 0, just like on second loop where i = 1, i outputted i just before exception is thrown already. Edit0: i tried hardcoding i anyway, set to 1, filled cc1List 5 times with "add" call, still same error. :/ – 1lsvks5w2l Sep 30 '21 at 19:09
  • 1
    You are talking about code we can't see. You have to post the code that can reproduce the exception for us. – LarsTech Sep 30 '21 at 19:13
  • 1
    Why not just use the List Remove methods? https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeat?view=net-5.0 – Hursey Sep 30 '21 at 20:15
  • @1lsvks5w2l you don't need a public variable for the count. Just use cc1List.Count - 1 – HardCode Sep 30 '21 at 20:46

1 Answers1

0

Since you know what index you want to remove, use the RemoveAt method.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim lst As New List(Of TextBox) From {TextBox1, TextBox2, TextBox3, TextBox4}
    Dim IndexToRemove = 1
    lst.RemoveAt(IndexToRemove)
    For Each TB In lst
        Debug.Print(TB.Name)
    Next
End Sub

Prints

TextBox1
TextBox3
TextBox4

in the Immediate Window

Mary
  • 14,926
  • 3
  • 18
  • 27