Bind Gridview Using CSV File In ASP.NET

I have often read the common question in forum posts of how to bind a GridView from CSV file records but no one has provided the proper solution and many solutions contain a lot of code that is not required so by considering the preceding requirements I have decided to write this article to provide the solution to bind a GridView from CSV file records with a minimum amount of code. So let us start creating an application so beginners can also understand. First create the CSV file named Employee as:
 
 Now we have records to bind to the GridView, let us create the sample web application as follows:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
  3. Provide the web site a name such as "BindGridviewFromCSVFileRecords" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer and select "Add New Item" and Add Web Form.
  5. Drag and drop one Button, a GridView and a FileUploader control onto the <form> section of the Default.aspx page.
Now the default.aspx page source code will look such as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>Article by Vithal Wadje</title>  
</head>  
<body bgcolor="blue">  
    <form id="form1" runat="server">  
    <div style="color: White;">  
        <h4>  
            Article for C#Corner  
        </h4>  
        <table>  
            <tr>  
                <td>  
                    Select File  
                </td>  
                <td>  
                    <asp:FileUpload ID="FileUpload1" runat="server" />  
                </td>  
                <td>  
                </td>  
                <td>  
                    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />  
                </td>  
            </tr>  
        </table>  
        <br />  
        <br />  
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">  
            <AlternatingRowStyle BackColor="White" />  
            <EditRowStyle BackColor="#7C6F57" />  
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
            <RowStyle BackColor="#E3EAEB" />  
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
            <SortedAscendingCellStyle BackColor="#F8FAFA" />  
            <SortedAscendingHeaderStyle BackColor="#246B61" />  
            <SortedDescendingCellStyle BackColor="#D4DFE1" />  
            <SortedDescendingHeaderStyle BackColor="#15524A" />  
        </asp:GridView>  
    </div>  
    </form>  
</body>  
</html> 
The entire code of the default.aspx.cs page will look as follows:
using System;  
using System.IO;  
using System.Data;  
public partial class _Default : System.Web.UI.Page  
{  
      
    protected void Page_Load(object sender, EventArgs e)  
    {  
  
    }  
    protected void Button1_Click(object sender, EventArgs e)  
    {  
        //Creating object of datatable  
        DataTable tblcsv = new DataTable();  
        //creating columns  
        tblcsv.Columns.Add("Name");  
        tblcsv.Columns.Add("City");  
        tblcsv.Columns.Add("Address");  
        tblcsv.Columns.Add("Designation");  
         //getting full file path of Uploaded file  
        string CSVFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);  
        //Reading All text  
        string ReadCSV = File.ReadAllText(CSVFilePath);  
        //spliting row after new line  
        foreach (string csvRow in ReadCSV.Split('\n'))  
        {  
            if (!string.IsNullOrEmpty(csvRow))  
            {  
                //Adding each row into datatable  
                tblcsv.Rows.Add();  
                int count = 0;  
                foreach (string FileRec in csvRow.Split(','))  
                {  
                    tblcsv.Rows[tblcsv.Rows.Count - 1][count] = FileRec;  
                    count++;  
                }  
            }  
            //Calling Bind Grid Functions  
            Bindgrid(tblcsv);  
            
        }  
    }  
    //Function to bind gridview  
    private void Bindgrid(DataTable csvdt)  
    {  
        GridView1.DataSource = csvdt;  
        GridView1.DataBind();  
    }  
}   
Now run the application and the UI will look as follows: 
 
 
 
Now select the file by using the browse button as:
 
 
Now click on the Upload button. The records in the GridView will then look as in the following:
 
 
Now you have seen how the records are displayed in the GridView using a CSV file with a minimal amount of code and effort.
 
Note
  • Do a proper validation such as date input values when implementing.
Summary
From all the preceding examples you have learned how to bind a GridView using CSV file records. I hope this article is useful for all readers, if you have a suggestion then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode