Tuesday, September 14, 2010

How you can use csv file as data source of gridview

   
  --- Image show the example of csv file-------------------------------
Here I will show how you can use csv file as data source of gridview.

Demo.csv file
firstname,lastname
hiren,soni
kirtan,patel
sanjay,parmar
ghanu,nayak

Output:







//  get all lines of csv file
        string[] str = File.ReadAllLines(Server.MapPath("demo.csv"));

        // create new datatable
        DataTable dt = new DataTable();
        // get the column header means first line
        string[] temp = str[0].Split(',');
        // creates columns of gridview as per the header name
        foreach(string t in temp)
        {
          dt.Columns.Add( t , typeof(string));
        }
         // now retrive the record from second line and add it to datatable
        for(int i=1;i<str.Length;i++)
        {
            string[] t = str[i].Split(',');
            dt.Rows.Add(t);

        }
        // assign gridview datasource property by datatable
        GridView1.DataSource = dt;
        // bind the gridview
        GridView1.DataBind();

No comments:

Post a Comment