2016-09-09 132 views
0

我的代碼只獲取一行的值。但是我的用戶將文本寫入多行,我必須將所有值寫入JSON中。我怎樣才能得到所有行的值?Datagridview從所有行中獲取值

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

回答

2

在這種情況下,你應該使用dataGridView1.SelectedRowsSelectedRows屬性來獲取行。遍歷所有的行,做你喜歡的處理

foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
{ 
    //whatever you are currently doing 
} 
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); 
+0

var llist = new List (); 的foreach(的DataGridViewRow行中dataGridView1.Rows) { VAR OBJ =新Nachrichten_Felder() { Nachricht = row.Cells [ 「Nachricht」]。Value.ToString(), 基準= row.Cells [ 「原點」 ] .Value.ToString() }; llist.Add(obj); }突然退出,在Log中我可以看到「system.NullReference Exception」 – Francis

0

您需要遍歷數據網格採集得到的每一行。類似這樣的:

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