首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# DataGridViewRow to Json

C# DataGridViewRow to Json
EN

Stack Overflow用户
提问于 2015-11-27 03:25:49
回答 2查看 1K关注 0票数 0
代码语言:javascript
复制
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);

这是我的datagridview和

代码语言:javascript
复制
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。但我不能这么做。

EN

回答 2

Stack Overflow用户

发布于 2015-11-27 07:14:17

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

代码语言:javascript
复制
        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);
票数 1
EN

Stack Overflow用户

发布于 2015-11-27 06:57:47

Json.NET让这一切变得更容易。

例如:

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33945782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档