Click here to Skip to main content
Click here to Skip to main content

Reading a remote CSV and displaying it in a GridView

, 6 Jul 2009
Rate this:
Please Sign up or sign in to vote.
How to display a remote CSV file and bind it to a GridView without downloading or storing it temporaraily.

Introduction

This article explains how to display a remote CSV file and bind it to a GridView without downloading or storing it temporaraily. Also, I have included how to read a local CSV and bind it to a GridView.

Using the code

We have to follow just a few steps to achieve it. First, make a web request to the URL of the CSV file. After retrieving the response into a StreamReader, retrieve the first row from the StreamReader and make a table with the column specified in the first row of the CSV file. Retrieve the data row by row and adds the rows to the table. Bind the GridView after adding all the rows to the DataTable. That is it. Here is the code:

//to display remote csv file
protected void btnDispRemote_Click(object sender, EventArgs e)
{
    try
    {
        System.Net.HttpWebRequest WebRequest;
        string URL = txtRemote.Text.Trim(); //URL of the remote csv
        Uri CSVUri = new Uri(URL);

        WebRequest = (System.Net.HttpWebRequest)
                      System.Net.HttpWebRequest.Create(CSVUri);
        if ((WebRequest.GetResponse().ContentLength > 0))
        {
            System.IO.StreamReader strReader = 
              new System.IO.StreamReader(
              WebRequest.GetResponse().GetResponseStream());
            
            //create datatable with column names
            CreateCSVTable(strReader.ReadLine());
            String SingleLine;
            while ((SingleLine = strReader.ReadLine()) != null)
            {
                AddRowCSVTable(SingleLine);
                //adding rows to datatable
            }

            grdList.DataSource = CSVTable;
            grdList.DataBind();

            if (strReader != null) strReader.Close();
        }
    }
    catch (System.Net.WebException ex)
    {
        lblMsg.Text = "File does not exist.";
    }
}

We have two separate methods for creating the DataTable from the CSV data and to add row wise data to the DataTable. These two methods are as follows:

//to create the data table with columns
public void CreateCSVTable(string TableColumnList)
{
    CSVTable = new DataTable("CSVTable");
    DataColumn myDataColumn;
    string[] ColumnName = TableColumnList.Split(',');
    for (int i = 0; i < ColumnName.Length - 1; i++)
    {
        myDataColumn = new DataColumn();
        myDataColumn.DataType = 
           Type.GetType("System.String");
        myDataColumn.ColumnName = ColumnName[i];
        CSVTable.Columns.Add(myDataColumn);
    }
}

//to add the rows to datatable
public void AddRowCSVTable(string RowValueList)
{
    string[] RowValue = RowValueList.Split(',');
    DataRow myDataRow;
    myDataRow = CSVTable.NewRow();
    for (int i = 0; i < RowValue.Length - 1; i++)
    {
        myDataRow[i] = RowValue[i];
    }
    CSVTable.Rows.Add(myDataRow);
}

To display a CSV file residing on the system or an application folder, we can easily use simple steps to create an OLEDB connection, command, and adaptor. Sample code is shown below:

//to display local csv file
protected void btnDispLoc_Click(object sender, EventArgs e)
{
    string filename=fl.PostedFile.FileName.ToString();
    FileInfo file = new FileInfo(filename);
    string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
           "Data Source=\"" + file.DirectoryName + 
           "\";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';";
    OleDbConnection con = new OleDbConnection(ConnectionString);
    OleDbCommand cmd = new OleDbCommand(string.Format(
      "SELECT * FROM [" + file.Name + "]", file.Name), con);
    try
    {
        con.Open();
        OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable("CSVTable");
        oda.Fill(dt);
        grdList.DataSource = dt;
        grdList.DataBind();
    }
    catch (Exception ee)
    {
        lblMsg.Text = ee.Message;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

rahul_bit
Web Developer
India India
No Biography provided

Comments and Discussions

 
QuestionError from Reading a remote CSV and displaying it in a GridView PinmemberMember 981110116-Jan-14 13:56 
GeneralWow...saw this in my inbox - was working on something just like it recently PinmemberSteve Krile14-Jul-09 1:11 
Generalgood as a starter PinmemberJean-Paul Mikkers6-Jul-09 11:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 6 Jul 2009
Article Copyright 2009 by rahul_bit
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid