Hernán Casillas Hernán Casillas - 3 years ago 169
C# Question

How to handle this ArgumentOutOfRangexception?

I'm trying to make a program that reads a file with 50 random words, it stores the words with 3 letters or less in a list called SmallWords and the words with 4 letters or more in a list called LargeWords. I'm using Windows Forms and I have a ListView control with 2 columns... 'Small Words' and 'Large Words'. It seems obvious that what I want to do is just put the words in its corresponding column. The thing is that the file doesn't have like 25 small and 25 large words, you know? Maybe it has 30 small words and 20 large words, so when I do this loop to add items to the ListView, it throws this exception:

ArgumentOutOfRangeException.

This is my code

var MaxNum = Math.Max(SmallWords.Count, LargeWords.Count);

for (var index = 0; index < MaxNum; index++)
{
ListViewItem item = new ListViewItem(SmallWords[index]);
item.SubItems.Add(LargeWords[index]);
listView1.Items.Add(item);
}


The exception is thrown at this line
item.SubItems.Add(LargeWords[index]);


Is there a way to handle this? Or like another way to add the items to the columns? I know it works because if change
Math.Max(...);
to
Math.Min(...)
it adds the words but just the 20 large words and 20 small words, I'm going to be missing 10 small words in the SmallWords column.

Thanks

Answer Source

I think you should look at this problem in a different way. Basically you are adding a large word at i index to a small word at the same index. Which means that you have to have a SmallWord to add a LargeWord as a subitem. Forget finding the min or max, just loop through the count of SmallWords and only add the LargeWords if the index is in range:

for (var index = 0; index < SmallWords.Length; index++)
{
    ListViewItem item = new ListViewItem(SmallWords[index]);
    if(index < LargeWords.Length)
    {
        item.SubItems.Add(LargeWords[index]);
    }
    listView1.Items.Add(item);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download