Visual Studio C# index errors

1

When I'm running this code:

for(int i=0; i<list.Count; i++)
{
     if (list[i].Text.Equals(pid))
     {
        //....
     }
}

I get an error 'index out of bounds', but when using the debugger I can see that:

list.Count = 56
i=55

What's causing this error? it seems illogical.

Edit: As requested, a more detailed piece of code:

            for (int i = 0; i < list.Count; i++)
            {
                if (list != null)
                {
                    **if (list[i] != null)
                    {
                        if (list[i].Text.Equals(pid))
                        {
                            return i;
                        }
                    }
                }
            }

List is from a listView.Items The marked line is where the error is. And again, the values are:

list.Count = 258
i = 257

Exception:

System.ArgumentOutOfRangeException occurred
  HResult=0x80131502
  Message=Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  Source=mscorlib
  StackTrace:
   at System.Collections.ArrayList.get_Item(Int32 index)
   at System.Windows.Forms.ListView.ListViewNativeItemCollection.get_Item(Int32 displayIndex)
   at System.Windows.Forms.ListView.ListViewItemCollection.get_Item(Int32 index)
   at CANsniffer.Form1.FindPID(ListViewItemCollection list, String pid) in x/Form1.cs:line 170
   at CANsniffer.Form1.parseData(String inData) in x\Form1.cs:line 295
   at CANsniffer.Form1.DataReceivedHandler(Object sender, SerialDataReceivedEventArgs e) in x/Form1.cs:line 408
   at System.IO.Ports.SerialPort.CatchReceivedEvents(Object src, SerialDataReceivedEventArgs e)
   at System.IO.Ports.SerialStream.EventLoopRunner.CallReceiveEvents(Object state)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

And if I use watch to see the values of list, I get:

ActualValue: null
Message: index was out of range

Also, these issues are somewhat related to this post: Windows Forms ListView runtime errors

c#
visual-studio
asked on Stack Overflow Nov 11, 2017 by Joe Dock • edited Nov 11, 2017 by Joe Dock

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0