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。但我不能这么做。
发布于 2015-11-27 07:14:17
最快的方法是使用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);发布于 2015-11-27 06:57:47
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);https://stackoverflow.com/questions/33945782
复制相似问题