0

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();
        }
}
4
  • Are come columns maybe null? Commented Jul 20, 2022 at 19:52
  • Does this answer your question? How to unapply a migration in ASP.NET Core with EF Core Commented Jul 20, 2022 at 19:59
  • 3
    @AliSalehi did you comment on the wrong question? Commented Jul 20, 2022 at 20:09
  • The data is written to the database, and the dataGridView1 control is bound to the database to obtain data. Commented Jul 28, 2022 at 11:10

2 Answers 2

0

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();
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

how do i remove the extra "|" at the end of the row in the text file its not supposed to be there shown in this text file "txt|txt|txt|"
Please see the edit. You may want to consider using a third party CSV library. CSVHelper is one option and it may make things easier for you.
0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.