Steven
Steven

Reputation: 459

C# DataGridViewRow to Json

DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Add(chk);
chk.HeaderText = "Check";
chk.Name = "chk";
dataGridView1.ColumnCount =4;
dataGridView1.Columns[1].Name = "Product ID";
dataGridView1.Columns[2].Name = "Product Name";
dataGridView1.Columns[3].Name = "Product Price";


string[] row = new string[] {null, "1", "Product 1", "1000" };
dataGridView1.Rows.Add(row);
row = new string[] { null, "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { null, "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { null, "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);

This my datagridview and

List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (Convert.ToBoolean(row.Cells[chk.Name].Value) == true)
    {
        rows_with_checked_column.Add(row);
    }
}

this array (List<DataGridViewRow>) include my checked row. I want to convert List<DataGridViewRow> to Json. but I can't do that.

Upvotes: 0

Views: 1934

Answers (2)

mwilczynski
mwilczynski

Reputation: 3082

The fastest way would be with Json.NET (just download NuGet for this package). Also, I hardly can see your code working as you posted it. You need to cast each element of DataGridViewRowCollection to DataGridViewRow to create List you want to use.

        List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();

        foreach (var dgvrow in dataGridView1.Rows)
        {
            var casted = dgvrow as DataGridViewRow;
            if (casted == null) continue;
            rows_with_checked_column.Add(casted);
        }

        string json = JsonConvert.SerializeObject(rows_with_checked_column);

Upvotes: 1

jhmt
jhmt

Reputation: 1421

Json.NET makes it easier.
For example:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

JArray products = new JArray();
foreach (var row in rows_with_checked_column)
{
    JObject product = JObject.FromObject(new
    {
        ID = row.Cells[1].Value,
        Name = row.Cells[2].Value,
        Price = row.Cells[3].Value
    });
    products.Add(product);
}

string json = JsonConvert.SerializeObject(products);

Upvotes: 0

Related Questions