Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET

Reading a remote CSV and displaying it in a GridView

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
6 Jul 2009CPOL 45.5K   1.1K   22   4
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:

C#
//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:

C#
//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:

C#
//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)


Written By
Web Developer TATA Communications
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionC# Store Data from URL to SQL table Pin
Member 131508597-May-17 23:23
Member 131508597-May-17 23:23 
QuestionError from Reading a remote CSV and displaying it in a GridView Pin
Member 981110116-Jan-14 13:56
Member 981110116-Jan-14 13:56 
GeneralWow...saw this in my inbox - was working on something just like it recently Pin
Steve Krile14-Jul-09 1:11
Steve Krile14-Jul-09 1:11 
Generalgood as a starter Pin
jpmik6-Jul-09 11:48
jpmik6-Jul-09 11:48 

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

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