Click here to Skip to main content
12,397,059 members (68,505 online)
Rate this:
 
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];
                        lvi.SubItems.Add(data[1]);
                        lvi.SubItems.Add(data[2]);
                        if (data[3] != null) //Index out of range exception thrown here!
                        {  
                            lvi.SubItems.Add(data[3]);
                                              
                        }
                        listView1.Items.Add(lvi);
                    }
                    
                }
            }
        }
Posted 25-Jan-13 1:50am

1 solution

Rate this: bad
 
good
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)
Try
if (data.Length >= 4)
  Permalink  
Comments
DaedalusAero 25-Jan-13 7:58am
   
Many thanks indeed. Perfect.
OriginalGriff 25-Jan-13 8:25am
   
You're welcome!
Milind_T 25-Jan-13 7:58am
   
Nice and fast catch that was :-)
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


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