我从数据库中填充了DataGridView
,我需要获取每一行并从中创建一个对象。我无法弄明白该怎么做。
DataGridView Columns: Name Price ProductId Condition MemberId Description
我的代码:
foreach(DataGridViewRow row in members_dg.rows)
{
foreach(DataGridViewCell cell in row.Cells)
{
// need to get info. This should show u what im looking for.
//string name = cell1.Text;
//string price = cell2.Text;
//etc
//Member member = new Member(name, price, ...);
}
}
答案 0 :(得分:2)
也许这个?
foreach(DataGridViewRow row in members_dg.rows)
{
// need to get info. This should show u what im looking for.
string name = row.Cells[0].Value.ToString(); // first column
string price = row.Cells[1].Value.ToString(); // second column
//etc
Member member = new Member(name, price, ...);
}
您不必遍历每个单元格,只需调用您所在行的单元格索引。
答案 1 :(得分:0)
if(cell.OwningColumn.IsDataBound)
{
Member member = new Member();
//switch statement or you can use reflection
switch(cell.OwningColumn.DataPropertyName)
{
case "name":
member.Name=cell.Value;//need cast
....
}
}