I export the datagridview records in csv file using code :
using (StreamWriter myFile = new StreamWriter(filename, false, Encoding.Default))
{
string sHeaders = "";
for (int j = 0; j < dGV.Columns.Count; j++)
{
if (dGV.Columns[j].Visible)
{
sHeaders = sHeaders.ToString() + dGV.Columns[j].HeaderText + ", ";
}
}
myFile.WriteLine(sHeaders);
// Export data.
for (int i = 0; i < dGV.RowCount; i++)
{
string stLine = "";
for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
{
if (dGV.Columns[j].Visible)
{
stLine = stLine.ToString() + dGV.Rows[i].Cells[j].Value.ToString() + ", ";
}
}
myFile.WriteLine(stLine);
}
}
}
But problem is if the value in the datagridviewcell is Harikrishna,Daxini then it will not exported properly,because there is comma in the cell value, but I have a need of including comma in the value.And it should export properly.How can I do that ? I tried with enclosing that value by double quotes and single quotes but it does not work.
Spaces between seperating commas and an opening double quote can cause issues with CSV. Replace code like
"val1", "val2"in your csv file with"val1","val2". That should fix your issue.