Reputation: 343
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);
Upvotes: 2
Views: 14429
Reputation: 41
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);
}
Upvotes: 1
Reputation: 51
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);
Upvotes: 1
Reputation: 77896
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
}
Upvotes: 4