【问题标题】:DataGridView row loop and cell data accessDataGridView 行循环和单元格数据访问
【发布时间】:2011-12-06 21:57:25
【问题描述】:

我有一个从数据库填充的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, ...);
    }
}

【问题讨论】:

    标签: c# loops datagridview


    【解决方案1】:

    也许是这个?

    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, ...);
    }
    

    您不必遍历每个单元格,只需调用您所在行的单元格索引即可。

    【讨论】:

    • 发现这很有帮助。当你在 VS 中查看数据结构时,实际使用的语法并不是很明显,至少对我来说是这样。
    【解决方案2】:
    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
            ....
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多