C# DataGridViewRow to Json

本文关键字:Json to DataGridViewRow | 更新日期: 2023-09-27 18:24:51

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);

这是我的数据网格视图和

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);
    }
}

这个数组(List<DataGridViewRow>(包括我的检查行。我想将List<DataGridViewRow>转换为 Json。但我做不到。

C# DataGridViewRow to Json

最快的方法是使用 Json.NET(只需下载此包的NuGet(。另外,我几乎看不到您的代码在您发布时工作。您需要将DataGridViewRowCollection的每个元素强制转换为DataGridViewRow以创建要使用的列表。

        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);

Json.NET 使它更容易。
例如:

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);