Datagridview从所有行获取值

时间:2016-09-09 20:02:06

标签: c# datagridview json.net

我的代码只获取一行的值。但我的用户将文本写入许多行,我必须获取所有值以将其写入JSON。如何从所有行获取值?

var llist = new List<MyClass>();
var obj = new MyClass()
{
    Nachricht = dataGridView1.CurrentRow.Cells["Value"].Value.ToString(),
    Datum = dataGridView1.CurrentRow.Cells["File"].Value.ToString()
};
llist.Add(obj);
string export = JsonConvert.SerializeObject(new { types = llist }, Formatting.Indented);
File.WriteAllText(@Settings.Default.folder + "\\" + "upload" + "\\" + "export.json", export);

3 个答案:

答案 0 :(得分:3)

在这种情况下,您应该使用SelectedRowsdataGridView1.SelectedRows属性获取行。遍历所有行并像

一样进行处理
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
  //whatever you are currently doing
}

答案 1 :(得分:1)

可能重复: Looping each row in datagridview

//Setup list object
var llist = new List<MyClass>();
//Loop through datagridview rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
   var obj = new MyClass()
         {
             Nachricht = dataGridView1.row.Cells["Value"].Value.ToString(),
             Datum = dataGridView1.row.Cells["File"].Value.ToString()
         };
         llist.Add(obj);
}
//Write out JSON file
string export = JsonConvert.SerializeObject(new { types = llist }, Formatting.Indented);
File.WriteAllText(@Settings.Default.folder + "\\" + "upload" + "\\" + "export.json", export);

答案 2 :(得分:1)

您需要遍历数据网格集合以获取每一行。像这样:

Foreach(DataGridViewRow dgvr in DataGridView1.Rows)
{
    var obj = new MyClass()
    {
        Nachricht = dgrv.Cells["Value"].Value.ToString(),
        Datum = dgrv.CurrentRow.Cells["File"].Value.ToString()
    }
    llist.Add(obj);
}