I'm trying to get all the rows of a datagrid in c # in JSON format.
With the following code I already get the correct JSON format but I do not get all the data from the datagrid.
Just send me the data from the last row of the datagrid, taking into account that the datagrid can have n number of rows with data then it is not working correctly (this example has 3 rows the datagrid but it only brings me the last row and the data it does not put them correctly).
Here I leave the code may not be too much what I lack but I can not find how.
public class Formatjson
{
public string Folio { get; set; }
public string Nombre { get; set; }
public string Apellido { get; set; }
}
public class ListJson
{
public List<Formatjson> Infodatagrid { get; set; }
}
So I go through the datagrid:
foreach (DataGridViewRow item in dataGridView2.Rows)
{
var RootObject = new ListJson();
RootObject.Infodatagrid = new List<Formatjson>();
var folio = new Formatjson() { Folio = Convert.ToString(dataGridView2.Rows[item.Index].Cells["Column5"].Value.ToString()) };
var nombre = new Formatjson() { Nombre = Convert.ToString(dataGridView2.Rows[item.Index].Cells["Column6"].Value.ToString()) };
var apellido = new Formatjson() { Apellido = Convert.ToString(dataGridView2.Rows[item.Index].Cells["Column7"].Value.ToString()) };
RootObject.Infodatagrid.Add(folio);
RootObject.Infodatagrid.Add(nombre);
RootObject.Infodatagrid.Add(apellido);
josnencode = JsonConvert.SerializeObject(RootObject);
}
This is the result in json format:
{
"Infodatagrid": [{
"Folio": "239",
"Nombre": null,
"Apellido": null
}, {
"Folio": null,
"Nombre": "Juan",
"Apellido": null
}, {
"Folio": null,
"Nombre": null,
"Apellido": "Perez"
}]
}
I should bring the Json with information from the 3 rows that I have in the datagrid.
EDITED
This is the image of the datagrid, if it helps, it's just a common datagrid.