-2

InvalidArgument=Value of '4' is not valid for 'index'. Parameter name: index

here is my code

   if (lvnames.Items.Count > 0)
   {
         for (int x = 0; x < lvScratch.Items.Count; x++)
         {
           **lvnames.Items[x].SubItems[4].Text = lvnamestemp.Items[x].SubItems[0].Text;**
         }
   }
   else
   {

            MessageBox.Show("No Record", "Empty", MessageBoxButtons.OK, MessageBoxIcon.Information);

   }

my lvnames.Items has 4 colums and my lvnamestemp has 3 columns

i got that error InvalidArgument=Value of '4' on the bold code when i run the code

cmd
  • 11,622
  • 7
  • 51
  • 61

2 Answers2

1

" my lvnames.Items has 4 colums "

But you are accessing the 5th column with this code:

lvnames.Items[x].SubItems[4]

0 1 2 3 4 (4 is the fifth item).

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
0

Pretty much all arrays and collections are zero-based in .NET. The actual number of columns in a ListView is irrelevant to the number of subitems in a ListViewItem; all that matters is the number of subitems you added. Usually they are the same though. If you have four columns then you probably added four subitems, so they will be at indexes 0, 1, 2 and 3. Obviously 4 is not a valid index then.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • Who cares about your C++? How's your C#? ;-) As I said, it really doesn't matter how many columns there are in the `ListView`. The `SubItems` collection of a `ListViewItem` is independent of that. All that matters is the number of subitems you added. Note that the item itself is its own first subitem. If index 4 is invalid then that means that you have added three or fewer subitems to the item. If you want to access the subitem at index 4 then you have to add one, i.e. you have to add at least four subitems to the item. – jmcilhinney Apr 08 '14 at 02:50
  • How many times can I say the same thing? The number of columns that you have added to your ListView is **IRRELEVANT**! All that matters is the number of subitems you have added to that item. You can add a hundred columns to your ListView if you want but if you only add two subitems to your item then you will only have subitems at indexes 0, 1 and 2. You haven't added enough subitems to the item. It's that simple. **STOP** thinking about the number of columns in the ListView because it has **ABSOLUTELY NOTHING** to do with your issue. – jmcilhinney Apr 08 '14 at 03:15