【问题标题】:How to read values from a DataGridView.Rows collection and assign them to a list of custom objects?如何从 DataGridView.Rows 集合中读取值并将它们分配给自定义对象列表?
【发布时间】:2014-05-12 02:03:41
【问题描述】:
我的自定义对象有两个属性:userid 和 username。
在这里,我找到了如何使用foreach 循环遍历每个DataGridViewRow,但我不知道如何将当前单元格值分配给我的自定义对象值。
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
ClsOBJ userobj1 = new ClsOBJ();
foreach (DataGridViewCell dc in dr.Cells)
{
// userobj1.userid =
// cell index 0 should be read to userid
// and cell index 1 should be read to username
// userobj1.username =
}
list1.Add(userobj1);
}
【问题讨论】:
标签:
c#
list
object
datagridview
custom-object
【解决方案1】:
无需遍历单元格集合。只需访问每一个并根据需要进行转换:
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
ClsOBJ userobj1 = new ClsOBJ();
userobj1.userid = Convert.ToInt32(dr.Cells[0].Value);
userobj1.username = Convert.ToString(dr.Cells[1]);
list1.Add(userobj1);
}
您可以使用LINQ 填充列表,但如果您不熟悉它,foreach 循环非常好。
list1.AddRange(
dataGridView1.Rows
.Cast<DataGridViewRow>()
.Select(x => new ClsOBJ
{
userid = Convert.ToInt32(x.Cells[0].Value),
username = Convert.ToString(x.Cells[1].Value)
}));