System.indexoutofrangeexception:'index超出了数组的范围。' [英] System.indexoutofrangeexception: 'index was outside the bounds of the array.'

查看:142
本文介绍了System.indexoutofrangeexception:'index超出了数组的范围。'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

得到错误:System.IndexOutOfRangeException:'索引超出了数组的界限。'就行:dr [headerWord] = dataWords [columnIndex ++];



HelP





getting the error: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' on the line : dr[headerWord] = dataWords[columnIndex++];

HelP


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.

推荐答案

index超出了数组范围 - Google搜索 [ ^ ]



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

dataWords[columnIndex++]





columnIndex对于dataWords中的项目数可能太大了。如果dataWords有3个项目



dataWords [0] = ..

dataWords [1] = ..

dataWords [2] = ..



和columnIndex大于或等于3,因为dataWords [3]无效,你会得到这个错误。



您假设您阅读的行具有所需的列数,显然它没有。在尝试访问其元素并确定要执行的操作时,您需要检查一个数组是否足够大。



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.


检查您的CSV文件。错误可能有多种原因。



一个是有一行比标题更少的列(逗号)。要检测到这一点,请将项目数与标题的项目数进行比较:

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:
if (dataWords.Length != headerLabels.Length)
{
    // Report error here and stop populating this row
}



另一个是第一行在引用字段中包含逗号。请注意,其他行上的这些字段(以逗号引用)会使您的代码无法按预期工作,即使不会发生初始错误。



处理此类引用字段您必须使用更复杂的方法从CSV行获取字段。在网上搜索c#split csv row之类的内容。



一个常见的解决方案是使用像 @这样的正则表达式? \ * *,\ s *?然后每两个连续双引号替换一个。


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.


这篇关于System.indexoutofrangeexception:'index超出了数组的范围。'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆