Reputation: 123
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);
}
Upvotes: 1
Views: 6220
Reputation: 359
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);
Upvotes: 0
Reputation: 2101
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();
Upvotes: 2
Reputation: 5136
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);
}
Upvotes: 6