Reputation:
I want to export DataGridView
to a text file. I write this code. It works fine but I want to write column headers to the textfile too.
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text File|*.txt";
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
StringBuilder builder = new StringBuilder();
int rowcount = dgvSum.Rows.Count;
int columncount = dgvSum.Columns.Count;
for (int i = 0; i < rowcount - 1; i++)
{
List<string> cols = new List<string>();
for (int j = 0; j < columncount - 1; j++)
{
cols.Add(dgvSum.Rows[i].Cells[j].Value.ToString());
}
builder.AppendLine(string.Join("\t", cols.ToArray()));
}
System.IO.File.WriteAllText(dialog.FileName, builder.ToString());
MessageBox.Show(@"Text file was created.");
Upvotes: 2
Views: 7396
Reputation: 39956
So you need this line before the first for
loop:
List<string> headerCols = new List<string>();
for (int j = 0; j < columncount - 1; j++)
{
headerCols.Add(dgvSum.Columns[j].HeaderText);
}
builder.AppendLine(string.Join("\t", headerCols));
for (int i = 0; i < rowcount - 1; i++)
{
....
....
Upvotes: 2
Reputation: 35680
I would use built-in functionality (GetClipboardContent()
method)
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text File|*.txt";
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
// setup for export
dgvSum.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dgvSum.SelectAll();
// hiding row headers to avoid extra \t in exported text
var rowHeaders = dgvSum.RowHeadersVisible;
dgvSum.RowHeadersVisible = false;
// ! creating text from grid values
string content = dgvSum.GetClipboardContent().GetText();
// restoring grid state
dgvSum.ClearSelection();
dgvSum.RowHeadersVisible = rowHeaders;
System.IO.File.WriteAllText(dialog.FileName, content);
MessageBox.Show(@"Text file was created.");
Upvotes: 4