Subscribe to Youtube channel

How to Import CSV File and bind csv file data to gridview in asp.net using c#

I am going to demonstrate in this article about importing CSV file data into datatable and then bind that data to Asp.net gridview control. I have tried to make code simpler and less line of code.

I am assuming that you have saved the csv file to server by using file-upload control.


  • After that create function which returns string[]


private IEnumerable<string[]> GetAllDataFromCSVFile(string FileName)
        {
            string str;
            using (StreamReader rd=new StreamReader(FileName))
            {
                while ((str = rd.ReadLine()) != null)
                {
                    yield return str.Split(',');
                }
            }
        }


  • Create another function which returns final data-table with CSV File data


private DataTable GetCSVData(string FileName)
        {
            var values = GetAllDataFromCSVFile(FileName);
                DataTable dt = new DataTable();
                int j=0;
                foreach (var item in values.FirstOrDefault())
                {
                    if (!dt.Columns.Contains(item))
                     {
                          dt.Columns.Add(item.Replace("\"",""));
                       j++;
                      }
                }
                var allvalues=values.Skip(1).ToList();
                for (int i = 0; i < allvalues.Count; i++)
                {
                    dt.Rows.Add(allvalues[i].Take(dt.Columns.Count).ToArray());
                //remove double quote from data
                for(int co=0;co<j;co++)
                {
                    dt.Rows[i][co] = dt.Rows[i][co].ToString().Replace("\"","");

                }

                }
                return dt;
        }


  • Now call GetCSVData function from Submit event


  protected void submit_Click(object sender,EventArgs e)
        {
            string FileName = "";
        //your file upload logic

            DataTable dt = GetCSVData(FileName);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }


Comments

  1. I got a small bug on your code at GetCSVData method, the fix is:

    dt.Rows[i][co] = dt.Rows[i][co].ToString().Replace("\"", "");

    ReplyDelete
    Replies
    1. Thank you Marcelo for your warm reply, i will correct the bug shortly.

      Delete
  2. what about fields with a comma? I have such fields capped with quotes... example..."City, State Zip"

    ReplyDelete

Post a Comment

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Devexpress Datebox date formatting in angular 6 with example

Disable backspace key using Jquery

Angular User Session Timeout example step by step

Restore the lost focus of Auto post back controls in asp.net update Panel control

Remove Owin from MVC 5 Application and use asp.net custom forms authentication

Clone a generic list in C# using extension method