2

My code only gets the values of one row. But my user writes text into many rows and I have to get all their values to write them into a JSON. How can I get the values from all rows?

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);
4444
  • 3,541
  • 10
  • 32
  • 43
Francis
  • 343
  • 2
  • 5
  • 16
  • Does this answer your question? [Looping each row in datagridview](https://stackoverflow.com/questions/19737436/looping-each-row-in-datagridview) – Tanner Jan 27 '20 at 16:55

3 Answers3

4

In that case you should get the rows from SelectedRows property using dataGridView1.SelectedRows. Loop through all the rows and do your processing like

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
  //whatever you are currently doing
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
1

Possible duplicate: 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);
Community
  • 1
  • 1
Tramel Jones
  • 51
  • 1
  • 5
  • var llist = new List(); foreach (DataGridViewRow row in dataGridView1.Rows) { var obj = new Nachrichten_Felder() { Nachricht = row.Cells["Nachricht"].Value.ToString(), Datum = row.Cells["Datum"].Value.ToString() }; llist.Add(obj); } Exits suddenly, in Log I can see "system.NullReference Exception" – Francis Sep 09 '16 at 21:00
1

You will need to loop through the data grid collection to get each row. Something like this:

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);
}
Aroidan
  • 41
  • 3