Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert contents of DataGridView to List in C#

What is the best way to grab the contents of a DataGridView and place those values into a list in C#?

like image 946
Joseph U. Avatar asked Nov 25 '10 21:11

Joseph U.


3 Answers

If you bind your list using DataSource, you can convert back by with:

List<Class> myClass = DataGridView.DataSource as List<Class>;
like image 168
Omer Avatar answered Oct 19 '22 13:10

Omer


        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);
        }
like image 13
Aaron McIver Avatar answered Oct 19 '22 12:10

Aaron McIver


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();
like image 4
user287107 Avatar answered Oct 19 '22 13:10

user287107