Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
getting the error: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' on the line : dr[headerWord] = dataWords[columnIndex++];

HelP


C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnParseDisplay_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();

            txtFilePath.Text = openFileDialog1.FileName;
            BindDataCSV(txtFilePath.Text);
        }

        private void BindDataCSV(string filePath)
        {
            DataTable dt = new DataTable();
            string[] lines = System.IO.File.ReadAllLines(filePath);
            if (lines.Length > 0)
            {
                //first line to create header

                string firstLine = lines[0];

                string[] headerLabels = firstLine.Split(',');

                foreach(string headerWord in headerLabels)
                {
                    dt.Columns.Add(new DataColumn(headerWord));
                }

                //for data

            for(int r = 1; r < lines.Length; r++)
                {
                    string[] dataWords = lines[r].Split(',');
                    DataRow dr = dt.NewRow();
                    int columnIndex = 0;
                    foreach (string headerWord in headerLabels)
                    {

                        dr[headerWord] =  dataWords[columnIndex++];
                    }

                    dt.Rows.Add(dr);

                    }
            }

            if (dt.Rows.Count > 0)
            {
                dgvEmployees.DataSource = dt;
            }
        }
    }
}


What I have tried:

everything I can think of. I have been googling for a week and my teacher is no help.
Posted
Updated 31-Jul-18 0:58am

index was outside the bounds of the array - Google Search[^]

C#
dataWords[columnIndex++]


columnIndex is probably too big for the number of items in dataWords. If dataWords have 3 items

dataWords[0] = ..
dataWords[1] = ..
dataWords[2] = ..

and columnIndex is greater than or equal to 3 you will get this error as dataWords[3] is invalid.

You are assuming that the line you read has the required number of columns and obviously it doesn't. You need to check an array is big enough before you try and access its elements and decide what you want to do when it isn't.
 
Share this answer
 
Check your CSV file. There may be multiple reasons for the error.

One is that there is a line having less columns (commas) than the header. To detect this compare the number of items to those of the header:
C#
if (dataWords.Length != headerLabels.Length)
{
    // Report error here and stop populating this row
}

Another is that the first line contains a comma within a quoted field. Note that such fields (quoted with comma) on other lines would make your code not work as expected even when the initial error would not occur.

To handle such quoted fields you have to use a more sophisticated method to get the fields from a CSV row. Search the net for something like "c# split csv row".

A common solution is to use a regular expression like @"""?\s*,\s*""?" and replace afterwards every two consecutive double quotes by a single one.
 
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