I would approach this slightly differently.
To generate the column names, I would use the original DataSet. Instead of using a for loop I would a foreach loop they ahve less over head then the for loops
eg.
let's assume that your dataset is called ds.
StringBuilder sb = new Stringbuilder();
int numColumns = Tables[0].Columns.Count-1
int columnCounter= numColumns;
foreach(DataColumn dc in ds.Tables[0].Columns)
{
sb.Append(dc.ColumnName);
AppendDelimiter(sb, ref columnCounter);
}
foreach(GridViewRow gvr in Datagidveiw1.Rows)
{
columnCounter=numColumns
foreach(TableCell c in grv.Cells)
{
sb.Append(c.Text)
AppendDelimiter(sb,ref columnCounter);
}
}
private void AppendDelimiter(StringBuilder sb, ref int columnCounter)
{
if (columnCounter > 0)
sb.Append(';');
else
sb.Append(Environment.NewLine);
columnCounter--;
}
do the rest of the code here to write content to file.
I have tested this and it worked just fine.
If you have any more issues then I would like to see the code that you use to construct your gridview and or a screenshot of the populated gridview.
Another alternative is to persit your changes in the gridview to the DataSet and then iterate through the DataSet.Table[0].Rows to create the csv.