Joseph U.
Joseph U.

Reputation: 4607

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#?

Upvotes: 16

Views: 61262

Answers (6)

Omer
Omer

Reputation: 10174

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

List<Class> myClass = DataGridView.DataSource as List<Class>;

Upvotes: 11

gmlogic
gmlogic

Reputation: 1

VB:

Dim lst As List(Of DataGridViewRow) = Me.MasterDataGridView.Rows.Cast(Of DataGridViewRow).AsEnumerable.ToList

C#:

List<DataGridViewRow> lst = this.MasterDataGridView.Rows.Cast<DataGridViewRow>.AsEnumerable.ToList;

Upvotes: 0

RBT
RBT

Reputation: 25877

IEnumerable.OfType<TResult> extension method can be your best friend here. Here is how I would have done it through a LINQ query:

List<MyItem> items = new List<MyItem>();
dataGridView1.Rows.OfType<DataGridViewRow>().ToList<DataGridViewRow>().ForEach(
                row =>
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        //I've assumed imaginary properties ColName and ColValue in MyItem class
                        items.Add(new MyItem { ColName = cell.OwningColumn.Name, ColValue = cell.Value });
                    }
                });

Upvotes: 1

Tim Jarvis
Tim Jarvis

Reputation: 18815

Or a linq way

var list = (from row in dataGridView1.Rows.Cast<DataGridViewRow>()
           from cell in row.Cells.Cast<DataGridViewCell>()
           select new 
           {
             //project into your new class from the row and cell vars.
           }).ToList();

Upvotes: 4

user287107
user287107

Reputation: 9418

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

Upvotes: 4

Aaron McIver
Aaron McIver

Reputation: 24713

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

Upvotes: 14

Related Questions