Save the DataGridView fields in an XML

2

I have a small problem that I can not solve, I have a GridView with 3 specific columns, what I need is to save those 3 columns in an XML and I can not do it.

The xml that I want to form is more or less like that.

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Fila1>
    <Columna1>Ejemplo</Columna1>
    <Columna2>Ejemplo</Columna2>
    <Columna3>Ejemplo</Columna3>
</Fila1>
<Fila2>
    <Columna1>Ejemplo</Columna1>
    <Columna2>Ejemplo</Columna2>
    <Columna3>Ejemplo</Columna3>
</Fila2>
<Fila3>
    <Columna1>Ejemplo</Columna1>
    <Columna2>Ejemplo</Columna2>
    <Columna3>Ejemplo</Columna3>
</Fila3>
</NewDataSet>

and the DataGridView that I have is this:

    
asked by Gerardo Anaya 15.05.2018 в 19:20
source

1 answer

0

The first thing you should do is save the grid data in a dataset. For that you can make an extension method so that it is available in any grid:

public static class DataGridViewExtensions
{
    public static DataSet GetDataSet(this DataGridView dgv) 
    {
        var ds = new DataSet();
        var dt = new DataTable();

        foreach (var column in dgv.Columns.Cast<DataGridViewColumn>()) 
        {
            if (column.Visible) 
            {
                dt.Columns.Add();
            }
        }

        var cellValues = new object[dgv.Columns.Count];
        foreach (var row in dgv.Rows.Cast<DataGridViewRow>()) 
        {
            for (int i = 0; i < row.Cells.Count; i++) 
            {
                cellValues[i] = row.Cells[i].Value;
            }
            dt.Rows.Add(cellValues);
        }
        ds.Tables.Add(dt)
        return ds;
    }
}

With that, when you want to save the grid information in an xml you do that:

var dataSet = dgvGrid.GetDataSet();
dataSet.WriteXml(File.OpenWrite("archivo.xml"));

dgvGrid is the grid that you want to export to xml, and "file.xml" is the path where you will save the xml.

I have not tried it in visual studio, it warns if you get an error.

    
answered by 15.05.2018 в 20:52