![](/img/trans.png)
[英]How to sort a DataGridView that is bound to a collection of custom objects?
[英]How to read values from a DataGridView.Rows collection and assign them to a list of custom objects?
我的自定义对象具有两个属性: 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);
}
无需遍历细胞集合。 只需访问每个文件并根据需要进行转换:
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)
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.