System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' 当我尝试在 C# 中将 csv 转换为 dataGridView

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' When I try to csv to dataGridView in C#

我正在尝试使用此方法导入 csv 文件并在数据网格中查看,但出现索引超出数组范围错误:( 请帮帮我。

    private void button1_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)
        {
            string firstLine = lines[0];
            string[] headerLabels = firstLine.Split(',');
            foreach (string headerWord in headerLabels)
            {
                dt.Columns.Add(new DataColumn(headerWord));
            }
            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++]; <-- here is the problem
                }
                dt.Rows.Add(dr);
            }
        }
        if (dt.Rows.Count > 0)
        {
            dataGridView1.DataSource = dt;
        }
    }
}

您的 header 行数与内容行数不匹配。

我认为您可以解决此问题以使用此代码块

 foreach (string headerWord in headerLabels)
 {
    if (dataWords.Length > columnIndex)
        dr[headerWord] = dataWords[columnIndex];
    else
        dr[headerWord] = "";
    
    columnIndex++;
 }