0

I would like to ask if you have a source code for importing csv files to gridview in an ASP.NET web form.

What I want to do is remove the header on the file and display it in the grid view.

Here is a SC of my file

enter image description here

TylerH
  • 20,799
  • 66
  • 75
  • 101
Miguel Intoy
  • 73
  • 11

1 Answers1

0

Read the CSV into a DataTable and then bind it into the GridView:

public void bindGrid()
{
var dt=GetDataTableFromCsv("path_to_csv_file",true);
GridView1.DataSource=dt;
GridView1.DataBind();
}

From How to read a CSV file into a .NET Datatable:

DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
    string header = isFirstRowHeader ? "Yes" : "No";

    string pathOnly = Path.GetDirectoryName(path);
    string fileName = Path.GetFileName(path);

    string sql = @"SELECT * FROM [" + fileName + "]";

    using(OleDbConnection connection = new OleDbConnection(
              @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + 
              ";Extended Properties=\"Text;HDR=" + header + "\""))
    using(OleDbCommand command = new OleDbCommand(sql, connection))
    using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
    {
        DataTable dataTable = new DataTable();
        dataTable.Locale = CultureInfo.CurrentCulture;
        adapter.Fill(dataTable);
        return dataTable;
    }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
A_Sk
  • 4,532
  • 3
  • 27
  • 51