I have some code which saves my datagrid to the 'C' directory as csv and it works fine.
The problem is I have to hard code the directory and I would like to use the save file dialog to do the same task.
It's nearly working but for some reason when I click save the below code throws up another save as window, I have a feeling I have doubled up on something.... Is there another way I should be coding the below within the save as dialog?
string CsvFpath = saveFileDialog1.FileName;
System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string columnHeaderText = "";
int countColumn = dataGridView1.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = dataGridView1.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns [i].HeaderText;
}
csvFileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in dataGridView1.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
}
csvFileWriter.WriteLine(dataFromGrid);
}
}
csvFileWriter.Flush();
csvFileWriter.Close();
MessageBox.Show("Export successful");
}