How to export to a txt file the REPEATED rows of a [Duplicated] DataGridView


I need to export everything that contains a DataGridView to txt files (each row a file) but in the case that a cell of a given column has the same value, those two rows must be exported in a single file.

At the moment I export the files that are selected

TextWriter tw = new StreamWriter(path, true);

for (int i = 0; i < TablaDatos.Rows.Count; i++)
    if (Convert.ToBoolean(TablaDatos.Rows[i].Cells[Exportar.Name].Value) == true)
        foreach (DataGridViewCell cell in TablaDatos.Rows[i].Cells)
            data += (cell.Value + "\t");
        data += "\n";


tw.WriteLine(data, "data");
MessageBox.Show("Datos exportados correctamente");

I need to export all the Grid that is one file per row, but, if they have the same category, export each row within a same txt file, if in the whole Grid there is only one file with category 8 for example, that row will be a txt file.

asked by AbregoW 01.03.2016 в 00:00

1 answer


The safest thing you already found was a solution to your problem, but I wanted to share a similar code that you can apply to your DataGridView control with some modifications, in my version, I used a class called Articulos and I made a list to divide it and an array of strings for the categories, it is worth mentioning that the example is in console.

public static void Main()
    int i = 0;
    while (i < Categorias.Length)
        Console.WriteLine("Filtrados por Categoria: " + Categorias[i]);
        foreach (Articulo n in Articulos)
            if (n.Categoria == Categorias[i])
                Console.WriteLine(n.ID + "\t" + n.Valor);

Where I used this data as input:

// Arreglo de categorias según necesidades.
public static string[] Categorias = new string[] { "Hogar", "Comida", "Ropa" };

public static IList<Articulo> Articulos = new List<Articulo>()
    new Articulo(1, Categorias[0], 100), new Articulo(2, Categorias[1], 200),
    new Articulo(3, Categorias[2], 500), new Articulo(4, Categorias[1], 300),
    new Articulo(5, Categorias[2], 800), new Articulo(6, Categorias[0], 400),
    new Articulo(7, Categorias[1], 100), new Articulo(8, Categorias[2], 750),
    new Articulo(9, Categorias[0], 690)

Which throws the following output:

Filtrados por Categoria: Hogar
1    100
6    400
9    690
Filtrados por Categoria: Comida
2    200
4    300
7    100
Filtrados por Categoria: Ropa
3    500
5    800
8    750

There I leave you the Link of the fiddle, I hope it helps you!

answered by 07.04.2016 в 15:50