how can I save all the data from a DataGridView in a txt file in C #

1

I already try to do it but it only saves me the first line (that of the titles) and I need to start saving from the second line to the bottom.

this is my code:

private void btnguardar_Click(object sender, EventArgs e)
{
    StreamWriter escribirenTxt = new StreamWriter(@"C:\Users\usuario\Desktop\Archivos.txt", true);
    try
    {
        escribirenTxt.WriteLine(Column1.HeaderText + "," + Column2.HeaderText + "," + Column3.HeaderText + "," + Column4.HeaderText + "," + "\n");
        MessageBox.Show("Registrado Exitosamente, C:/Users/usuarios/Desktop/Archivos.txt");
    }
    catch
    {
        MessageBox.Show("error al registrar...");
    }
    escribirenTxt.Close();
}
    
asked by Kenneth Alvarez 09.06.2018 в 10:48
source

1 answer

0

You can do it in this mode, it's a good practice also use the keyword in your panorama.

This code will loop your Grid and write the content in a text file, remember to choose the columns and what you want.

using (var writetext = new StreamWriter("C:\temp\write.txt"))
{
    foreach (DataGridViewRow row in dgvData.Rows)
    {
        writetext.WriteLine($"{row.Cells[0].Value}, {row.Cells[1].Value}, {row.Cells[2].Value}, {row.Cells[3].Value}" );
    }
}
    
answered by 09.06.2018 / 13:38
source