![](/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.