What is the best way to grab the contents of a DataGridView and place those values into a list in C#?
If you bind your list using DataSource, you can convert back by with:
List<Class> myClass = DataGridView.DataSource as List<Class>;
List<MyItem> items = new List<MyItem>();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
MyItem item = new MyItem();
foreach (DataGridViewCell dc in dr.Cells)
{
...build out MyItem....based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
}
items.Add(item);
}
var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
r => r.Cells.OfType<DataGridViewCell>().Select(c => c.Value).ToArray()).ToList();
or to get a string dictionary of the values
var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
r => r.Cells.OfType<DataGridViewCell>().ToDictionary(c => dataGridView1.Columns[c.OwningColumn].HeaderText, c => (c.Value ?? "").ToString()
).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With