0

I am trying with this method to import csv file and view in datagrid but I get Index was outside the bounds of the array error :( please help me out.

    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;
        }
    }
}
kewu
  • 3
  • 1
  • This particular error always has the same cause: you tried to index an array using either a negative number or a number that is greater than the size of the array minus one. Troubleshoot your code accordingly. – Robert Harvey Jul 18 '21 at 18:13
  • One of CSV content lines has less columns than the header indicates. – Hero Wanders Jul 18 '21 at 18:29

1 Answers1

0

Your header row count and content row count is not match.

I think you can fix this problem to use this code block

 foreach (string headerWord in headerLabels)
 {
    if (dataWords.Length > columnIndex)
        dr[headerWord] = dataWords[columnIndex];
    else
        dr[headerWord] = "";
    
    columnIndex++;
 }
Enes Kartal
  • 137
  • 1
  • 9