You have other problems you need to sort out first:
1) Don't use the DataGridView itself directly unless you really have to - use the underlying DataSource instead. That way, you get access to the actual data fields more easily.
2) Your column headers line ends with a spurious comma: consider using
string.Join[
^] instead of a manual loop.
if (myDataGridView.DataSource is DataTable dt)
{
string s = string.Join(",", dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName));
Console.WriteLine(s);
}
3) Your row data isn't separated by a comma at all! Again, string.Join is your friend here.
4) Strings are immutable in .NET: each time you try to add two strings, you cause a new memory allocation and two copy operations - which can get extremely time- and memory-consuming with large data sets. Use a
StringBuilder[
^] instead.
5) Instead of a "blanket" ToString operation to build the CSV row data, check the datatype: if it's a DateTime, then use a specific ToString to convert it.
if (myDataGridView.DataSource is DataTable dt)
{
List<string> csvReady = new List<string>(dt.Rows.Count + 1);
csvReady.Add(string.Join(",", dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName)));
List<string> rowData = new List<string>(dt.Columns.Count);
foreach (DataRow row in dt.Rows)
{
rowData.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
object cell = row[i];
if (cell.GetType() == typeof(DateTime))
{
rowData.Add(((DateTime)cell).ToString("yyyy/MM/dd"));
}
else
{
rowData.Add(cell.ToString());
}
}
csvReady.Add(string.Join(",", rowData));
}
string csv = string.Join("\n", csvReady);
}