How to convert the DataGridView content into a List<> of custom objects?

5.9k Views Asked by At

I'm working on a Windows Forms application, written with C#.

I found someone's suggestion on how to create a List<> from DataGridView control, but I need little more help on how to extract cell values.

Here is the code given; let's say two columns in the dataGridView1 are Name and Address.
How to build the List<ProjList> object?

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    ProjList = new List<ProjectMasterRec>();

    foreach (DataGridViewCell dc in dr.Cells)
    {
        // build out MyItem
        // based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
        // how do we code this?
    }

    ProjList.Add(item);
}
3

There are 3 best solutions below

0
Amit Bisht On BEST ANSWER

Try It this Way

Create a list of your class type

List<ProjectMasterRec>() ProjList = new List<ProjectMasterRec>(); 

Make Sure that type of list belongs to type of your data in Datagridview

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    //Create object of your list type pl
    ProjectMasterRec pl = new ProjectMasterRec();
    pl.Property1 = dr.Cells[1].Value;
    pl.Property2 = dr.Cells[2].Value;
    pl.Property3 = dr.Cells[3].Value;

    //Add pl to your List  
    ProjList.Add(pl);     
}
2
Channs On

If you are able to use LINQ, you can do something like this:

var projectList = (from row in dataGridView1.Rows.OfType<DataGridViewRow>()
                   select new ProjectMasterRec() 
                   { Name = row.Cells["Name"].Value.ToString(),
                     Address = row.Cells["Address"].Value.ToString() 
                   }).ToList();
0
Y Stroli On

The following should work, myArray should be an array of the type you need, you can find out the array size using (DataGrid1.DataSource as BindingSource).List.Count.

(DataGrid1.DataSource as BindingSource).List.CopyTo(myArray, 0);