I'm using Following code to read CSV file contents.
http://www.sendspace.com/file/l0zki3 link to download CSV file..
This is the CSV file which is located in my C:\ Drive.
The exception I am getting is "Input array is longer than the number of columns in this table". Why might this happen?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO; //stremreader.. is frm.. System.IO.. ..
namespace csvtodatagridview
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ShowData()
{
Boolean flg=true;
string deli = ",";
string tbname = "Booktb"; //dataset .. used 2 stored. then move dataset to .. grid..
string filename = ("C:\\SharedIncidents.csv"); // path. plz keep the same path. ..
string str = Convert.ToString(System.DateTime.Now);
DataSet ds = new DataSet();
StreamReader sr = new StreamReader(filename); //Inputoutput .function 2 read.. file..
ds.Tables.Add(tbname); //add 2 table..
ds.Tables[tbname].Columns.Add("Date"); //specify. colum1 for datagrid1.
ds.Tables[tbname].Columns.Add("Status" );//specify colum2 for datagrid2.
ds.Tables[tbname].Columns.Add("Assignee" );
ds.Tables[tbname].Columns.Add("Response" );
string alldata = sr.ReadToEnd();
string[] rows = alldata.Split("\n".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(deli.ToCharArray());
ds.Tables[tbname].Rows.Add(items);
}
int count = ds.Tables[tbname].Rows.Count;
int index = 0;
int currentindex = 0;
for (index = 0; index < count; index++)
{
if (ds.Tables[tbname].Rows[index][0].Equals(str))
{
flg = true;
DataSet ds1 = new DataSet();
ds1.Tables.Add(tbname);
ds1.Tables[tbname].Columns.Add("Date"); //specify. colum1 for datagrid1.
ds1.Tables[tbname].Columns.Add("Status");//specify colum2 for datagrid2.
ds1.Tables[tbname].Columns.Add("Assignee");
ds1.Tables[tbname].Columns.Add("Response");
currentindex = index;
while (currentindex < count)
{
DataRow row = ds.Tables["tbname"].Rows[currentindex];
ds1.Tables[tbname].Rows.Add(row);
currentindex++;
}
break;
}
}
if (flg == false)
Console.WriteLine("Date not matched");
else
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
private void button1_Click(object sender, EventArgs e)
{
ShowData(); // call the abv function. .
}
}
}