I am trying to get in JSON format all the rows of a datagrid in c#.
With the following code I can already get the correct JSON format but I don't get all the data from the datagrid.
It only sends me the data of the last row of the datagrid, taking into account that the datagrid can have n number of rows with data, so it is not working correctly for me (this example has 3 rows in the datagrid but it only brings me the last row and the data does not put them correctly).
Here I leave the code, maybe it's not too much what I'm missing but I can't 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; }
}
This is how I loop 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"
}]
}
It should bring me the Json with information of 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.
You don't have to put all the code inside the foreach, it would be something like this
as you will see the list is instantiated outside the loop
If you use this way to load data into your DataGridView:
You could do this:
Cheers