Click here to Skip to main content
12,951,732 members (72,230 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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? :)

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 25-Jan-13 7:58am
Many thanks indeed. Perfect.
Milind_T 25-Jan-13 7:58am
Nice and fast catch that was :-)
OriginalGriff 25-Jan-13 8:25am
You're welcome!
OriginalGriff 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 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
Top Experts
Last 24hrsThis month
OriginalGriff 6,229
CHill60 3,490
Maciej Los 3,083
Jochen Arndt 1,975
ppolymorphe 1,880

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 25 Jan 2013
Copyright © CodeProject, 1999-2017
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