Why do you go with Stream Reader stuff and go through each and every column.
Let me explain a simplified approach:
void PopulateGrid()
{
Microsoft.Win32.OpenFileDialog lObjFileDlge = new Microsoft.Win32.OpenFileDialog();
lObjFileDlge.Filter = "CSV Files|*.csv";
lObjFileDlge.FilterIndex = 1;
lObjFileDlge.Multiselect = false;
string fName = "";
bool? lBlnUserclicked = lObjFileDlge.ShowDialog();
if (lBlnUserclicked != null || lBlnUserclicked == true)
{
fName = lObjFileDlge.FileName;
}
if (!System.IO.File.Exists(fName))
return;
this.SuspendLayout();
DataGridView dataGrid1 = new DataGridView();
dataGrid1.AutoGenerateColumns = true;
dataGrid1.AllowUserToDeleteRows = true;
dataGrid1.AllowUserToAddRows = true;
dataGrid1.AllowUserToOrderColumns = true;
dataGrid1.Height = 250;
dataGrid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGrid1.ScrollBars = ScrollBars.Both;
dataGrid1.Location = new System.Drawing.Point(10, 120);
dataGrid1.DataSource =this.GetData(fName, true);
this.Controls.Add(dataGrid1);
this.ResumeLayOut();
}
public DataTable GetData(string path, bool firstRowHeader)
{
if (!File.Exists(path))
return null;
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
string withHeaderconnString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
string NoHeaderconnString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=No;FMT=Delimited\"";
string connString = NoHeaderconnString;
if (firstRowHeader)
connString = withHeaderconnString;
string query = "SELECT * FROM " + file;
DataTable dTable = new DataTable("Contacts");
OleDbDataAdapter dAdapter =
new OleDbDataAdapter(query, connString);
try
{
dAdapter.Fill(dTable);
}
catch (InvalidOperationException )
{ }
dAdapter.Dispose();
return dTable;
}