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和
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。但我不能这样做。
答案 0 :(得分:0)
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);
答案 1 :(得分:0)
最快的方法是使用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);