I have code that allows you to save datagrid information in visual studio into a text file but the datagrid is filled out and it just shows nothing in the text file
Code:
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled.txt";
sfd.DefaultExt = "txt";
sfd.Filter = "txt files (*.text) |*.txt*";
if (sfd.ShowDialog() == DialogResult.OK)
{
Stream fileStream = sfd.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
for(int i = 0; i < dataGridView1.Rows.Count - 1; i ) //rows
{
for (int j = 0; j < dataGridView1.Columns.Count; j ) // columns
{
sw.Write("\t", dataGridView1.Rows[i].Cells[j].Value.ToString() "\t" "|");
}
sw.WriteLine("");
}
sw.Close();
fileStream.Close();
}
}
CodePudding user response:
In my small tests, it appears the “\t” is getting misinterpreted. Fortunately, a simple fix is to simply make a Tab string
and use it like…
string tab = "\t";
Then…
sw.Write( tab dataGridView1.Rows[i].Cells[j].Value.ToString() tab "|");
In addition, it is a good idea to implement using
statements to ensure the resources get closed and disposed of properly. Something like…
private void button2_Click(object sender, EventArgs e) {
using (SaveFileDialog sfd = new SaveFileDialog()) {
sfd.FileName = "untitled.txt";
sfd.DefaultExt = "txt";
sfd.Filter = "txt files (*.text) |*.txt*";
string tab = "\t";
if (sfd.ShowDialog() == DialogResult.OK) {
using (Stream fileStream = sfd.OpenFile()) {
using (StreamWriter sw = new StreamWriter(fileStream)) {
for (int i = 0; i < dataGridView1.Rows.Count; i ) {
if (!dataGridView1.Rows[i].IsNewRow) {
for (int j = 0; j < dataGridView1.Columns.Count; j ) {
sw.Write(tab dataGridView1.Rows[i].Cells[j].Value.ToString());
if (j < dataGridView1.Columns.Count - 1) {
sw.Write(tab "|");
}
}
sw.WriteLine("");
}
}
//sw.Close();
//fileStream.Close();
}
}
}
}
}
CodePudding user response:
Here is an option
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace YourNamespaceGoesHere
{
public static class DataGridViewExtensions
{
public static void ExportRows(this DataGridView sender, string fileName, string defaultNullValue = "(empty)")
{
File.WriteAllLines(fileName, (sender.Rows.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => new {
row,
rowItem = string.Join(",", Array.ConvertAll(row.Cells.Cast<DataGridViewCell>()
.ToArray(), c => ((c.Value == null) ? defaultNullValue : c.Value.ToString())))
})
.Select(@row => @row.rowItem)));
}
}
}
Usage (replace the file name from your SaveFileDialog)
private void ExportButton_Click(object sender, EventArgs e)
{
dataGridView1.ExportRows("data1.txt");
}