Parsing a CSV into a DataGridView

  • Thread starter Thread starter GhostDZ9
  • Start date Start date
G

GhostDZ9

Guest
Hi All,

So I am building a CSV Parse that dynamically takes the data from the csv and puts it in a DataGridView. For the most part it is working fine however when it reads a line like the following:

"BMW, MÃ_nchen",,,,HEADQUARTERS : EMEA : Germany,Ralph Clausen,,CUSTOMER-Closed Won,,,No,,

It has an issue because of : "BMW, MÃ_nchen"

I am doing the Splitting by Comma hence the use of a CSV.

How do I get it to create an index of the array as 1 and ignore the comma within the quotes.

Below is my current code.

OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = "c:\\";
openFile.Filter = "txt files (*.txt)|*.txt| CSV Files (*.csv) | *.csv| All Files (*.*) | *.*";
openFile.FilterIndex = 2;
openFile.RestoreDirectory = true;
try {
if (openFile.ShowDialog() == DialogResult.OK)
{
string file = openFile.FileName;
StreamReader sr = new StreamReader(file);

/* gets all the lines of the csv */
string[] str = File.ReadAllLines(file);

/* creates a data table*/
DataTable dt = new DataTable();

/* gets the column headers from the first line*/
string[] temp = str[0].Split(,);

/* creates columns of the gridview base on what is stored in the temp array */
foreach (string t in temp)
{
dt.Columns.Add(t, typeof(string));
}

int count = 0;
/* retrieves the rows after the first row and adds it to the datatable */
for (int i = 1; i < str.Length; i++)
{
if (str.Contains("))
{
count++;

if (str.StartsWith("") && str.EndsWith(""))
{
string[] t = str.Split(");

// count++;
// MessageBox.Show(t);
}
//str[i + 1];

}
else
{
string [] t = str.Split(,);
dt.Rows.Add(t);
}

}
MessageBox.Show("Number of Rows with a Quote In it is: " + count);

/* assigns the data grid view a data source based on what is stored in dt */
dataGridView1.DataSource = dt;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: The CSV you selected could not be loaded" + ex.Message);
}


Please ask me if you need me to explain it further.


Regards,

Continue reading...
 
Back
Top