C# .NET - Parsing CSV into Data Grid - Asked By gopi Babu on 23-Feb-12 02:35 AM

Hi all

Thanks in advance

I having a scenario like I have to Parse the CSV file and have to Export the details in the CSV to a Datagridview. 

The CSV files is using "," as a delimiter i am parsing the CSV by using "," as a seperator. But the data in the CSV having comma in between the data this makes problem when i am seperating the fields using the delimiter "," how can handle this. can any one give ma a solution for this. 

Thanks and regards
Gopi Babu
kalpana aparnathi replied to gopi Babu on 23-Feb-12 03:27 AM
hi,

Here give you code for parsecsv to the list array after getting this list array bind your grid with this list

public List<string[]> parseCSV(string path)
{
  List<string[]> parsedData = new List<string[]>();
 
  try
  {
  using (StreamReader readFile = new StreamReader(path))
  {
    string line;
    string[] row;
 
    while ((line = readFile.ReadLine()) != null)
    {
    row = line.Split(',');
    parsedData.Add(row);
    }
  }
  }
  catch (Exception e)
  {
  MessageBox.Show(e.Message);
  }
 
  return parsedData;
}


After this code where you want to bind datagridview with resulting list like this:

dataGridView1.DataSource = list;

Read more:http://www.switchonthecode.com/tutorials/building-a-simple-csv-parser-in-csharp
Somesh Yadav replied to gopi Babu on 23-Feb-12 03:27 AM
please refer to links below:

   How to import CSV file into Grid http://www.netomatix.com/development/importcsvintogrid.aspx 

   Export DataGrid DataSet To CSV File http://www.netomatix.com/GridExportToCSV.aspx 

Hope these will help you!  

 If you still have any doubt and concern about this issue, please let me know. If I misunderstood you, please kindly elaborate your question.

gopi Babu replied to kalpana aparnathi on 23-Feb-12 07:26 AM
Hi friends 

Thanks for the spontaneous reply. The code you suggested to me working fine but my Content of the CSV file having comma in between 

For Eg.

"Wells Frago Bank, N.A"  - This is a content of a single column but when i parse this i am getting the data as two columns because the content having comma in between. This is the problem I am facing.

Kindly provide be a better solution.

Cheers

Gopi Babu