mike Delvotti

mike Delvotti

  • NA
  • 262
  • 0

Open CSV into Datagridview

Nov 27 2014 6:33 AM
Guys,

I'm trying to load a CSV into my datagridview and it nearly works, apart from the following error thrown: Input array is longer than the number of columns in this table.

On this line: dataset.Tables[tablename].Rows.Add(items);

Below is my event code am I missing something else from the above line?

                string delimiter = ",";
                string tablename = "Table";
                DataSet dataset = new DataSet();
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        filename = openFileDialog1.FileName;
                        StreamReader sr = new StreamReader(filename);
                        string csv = File.ReadAllText(openFileDialog1.FileName);
                        dataset.Tables.Add(tablename);
                        dataset.Tables[tablename].Columns.Add("Stock Number");
                        dataset.Tables[tablename].Columns.Add("Order Number");


                        string allData = sr.ReadToEnd();
                        string[] rows = allData.Split("\r".ToCharArray());

                        foreach (string r in rows)
                        {
                            string[] items = r.Split(delimiter.ToCharArray());
                            dataset.Tables[tablename].Rows.Add(items);
                        }
                        this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
                      }
            }

        public string filename { get; set; }


Answers (5)