Click here to Skip to main content
11,705,451 members (52,340 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
Hi people,

Can somebody please tellme why i'm getting an Index out of range exception with the following code.

The idea is that i want to read a CSV file and output the contents into a ListView. Columns 1, 2 and 3 are always data, column 4 is for notes and therefore does not alwasy contain data, hense my 'if (data[3] != null)'.

If i make sure all columns in the CSV have data, and remove the if statement, no problems! I'm clearly making a schoolboy error somewhere. Anybody like to show me where? Smile | :)

public void readFromCSV()
            using (FileStream fs = new FileStream("O:\\TestDaws\\CSDB\\Test2.csv", FileMode.Open, FileAccess.Read))
                using (TextReader sr = new StreamReader(fs))
                    string line;
                    while ((line = sr.ReadLine()) != null)
                        string[] data = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = data[0];
                        if (data[3] != null) //Index out of range exception thrown here!
Posted 25-Jan-13 1:50am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

It throws an error because you are trying to check a value that doesn't exist! Instead of
if (data[3] != null)
if (data.Length >= 4)
DaedalusAero at 25-Jan-13 7:58am
Many thanks indeed. Perfect.
OriginalGriff at 25-Jan-13 8:25am
You're welcome!
Milind_T at 25-Jan-13 7:58am
Nice and fast catch that was :-)
OriginalGriff at 25-Jan-13 8:26am
We've all done it - and I try to remember my mistakes (if only because Herself never forgets them either... :laugh:)
SChristmas at 25-Jan-13 8:37am
Good catch OriginalGriff

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 286
1 OriginalGriff 269
2 ppolymorphe 78
3 Inimicos 60
4 ProgramFOX 50
0 OriginalGriff 9,053
1 Sergey Alexandrovich Kryukov 8,347
2 CPallini 5,189
3 Maciej Los 4,726
4 Mika Wendelius 3,626

Advertise | Privacy | Mobile
Web03 | 2.8.150819.1 | Last Updated 25 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100