Datagridview - Datatable-Serialize

1

C # - I have a list of data in my Datagridview, what I'm looking for is that, when I click on the save button. all Datagridview data is stored in a datatable to be serialized and this is sent to the business layer and later to the data layers to be managed through a stored procedure. I hope your support.

    private void btnXml_Click(object sender, EventArgs e)
    {


         DataTable dt = new DataTable();
         DataSet ds = new DataSet();

         // Agregamos columnas a la tabla de datos

         foreach (DataGridViewColumn col in dvgClientes.Columns)

         {

             dt.Columns.Add(col.DataPropertyName, col.ValueType);

         }

         //agregamos nuevas filas

         foreach (DataGridViewRow row in dvgClientes.Rows)

         {

             DataRow row1 = dt.NewRow();

             for (int i = 0; i < dvgClientes.ColumnCount; i++)

                 //si el valor existe, agregue ese valor, de lo contrario agregue Nulo para ese campo

                 row1[i] = (row.Cells[i].Value == null ? DBNull.Value : row.Cells[i].Value);

             dt.Rows.Add(row1);

         }

         //Agregamos el datatable los datos

         ds.Tables.Add(dt);


    }
}
    
asked by Marco 21.01.2018 в 17:12
source

1 answer

0

It could be a better way to do it, but otherwise it would be quite trivial to just walk through the DGV and create the DataTable manually.

Something like this could work:

DataTable dt = new DataTable();
foreach(DataGridViewColumn col in dgv.Columns)
{
   dt.Columns.Add(col.Name);    
}

foreach(DataGridViewRow row in dgv.Rows)
{
    DataRow dRow = dt.NewRow();
    foreach(DataGridViewCell cell in row.Cells)
    {
        dRow[cell.ColumnIndex] = cell.Value;
    }
    dt.Rows.Add(dRow);
}
    
answered by 22.01.2018 в 15:32