Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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? :)


C#
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
Updated 11-Aug-22 23:54pm

It throws an error because you are trying to check a value that doesn't exist! Instead of
C#
if (data[3] != null)
Try
C#
if (data.Length >= 4)
 
Share this answer
 
Comments
DaedalusAero 25-Jan-13 7:58am    
Many thanks indeed. Perfect.
OriginalGriff 25-Jan-13 8:25am    
You're welcome!
MT_ 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:)
Sandesh M Patil 25-Jan-13 8:37am    
Good catch OriginalGriff
Thank you for this! I have similar issue, but where last data is not empty rather its empty in between.
Example: data[2] is empty, but there is data in data[3].
Please help!
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900