How do I manage to copy all rows of a datagridview in c # into a single text file?

0

I have a problem with my program. I need to make that when I copy all the rows of the DatagridView store them in the same file and display them in the order that they are in DatagridView , please I need your help. I share the code because at the moment it is just rewriting in the same file

private void button8_Click(object sender, EventArgs e)
{
    if (!Directory.Exists(@"C:\Users\GUSTAVO\Desktop\proyecto de restaurante\factura\"))
    {
        Directory.CreateDirectory(@"C:\Users\GUSTAVO\Desktop\proyecto de restaurante\factura\");
    }

    int rowcount = menu.Rows.Count;
    for (int i = 0; i < rowcount - 1; i++)
    {
        TextWriter sw = new StreamWriter(@"C:\Users\GUSTAVO\Desktop\proyecto de restaurante\factura\Archivo.txt");
        sw.WriteLine(menu.Rows[i].Cells[0].Value.ToString() + "\t"
                     + menu.Rows[i].Cells[1].Value.ToString() + "\t"
                      + menu.Rows[i].Cells[2].Value.ToString() + "\t"
                       + menu.Rows[i].Cells[3].Value.ToString() + "\t" + "\n");
        sw.Close();
    }
    MessageBox.Show(@"Datos Exportados correctamente");


}
    
asked by Lg Massella 24.05.2018 в 09:39
source

1 answer

1

Correct me if I'm wrong, but both the TextWriter and the .Close() should go out of the for. One above and one below:

int rowcount = menu.Rows.Count;
TextWriter sw = new StreamWriter(@"C:\Users\GUSTAVO\Desktop\proyecto de restaurante\factura\Archivo.txt");
for (int i = 0; i < rowcount - 1; i++)
{

    sw.WriteLine(menu.Rows[i].Cells[0].Value.ToString() + "\t"
                 + menu.Rows[i].Cells[1].Value.ToString() + "\t"
                  + menu.Rows[i].Cells[2].Value.ToString() + "\t"
                   + menu.Rows[i].Cells[3].Value.ToString() + "\t" + "\n");

}
sw.Close();

Otherwise you are opening a writer, rewriting the file and closing the writer for each row of your datagrid . With which your file will only contain the last row of the datagrid when it is being rewritten again and again.

    
answered by 24.05.2018 в 12:43