以编程方式将列表添加到datagridview

时间:2014-05-15 07:09:11

标签: c# datagridview

我有以编程方式将列表添加到datagridview的过程。例如:

public List<Color_INFO> addrowtocolors()
{    
    List<Color_INFO> result = dal.GetColor();
    for (int i = 0; i < list.Count; i++)
    {
         var index = grdColors.Rows.Add();
         grdColors.Rows[index].Cells["Code"].Value = result[i].Code.ToString();
         grdColors.Rows[index].Cells["Desc"].Value = result[i].Desc.ToString();
    }
    return null;
}

但是当我打电话给它时,它会向datagridview添加3行,而在列表中我只有一行。

我知道我可以使用数据集选项,但这不符合我的需要。

感谢名单。

1 个答案:

答案 0 :(得分:1)

根据我的评论......我也删除了返回值,因为返回null似乎很奇怪。 (甚至是基于您的函数名称的建议列表)。

public void addrowtocolors()
{    
    for (int i = 0; i < result.Count; i++)
    {
         var index = grdColors.Rows.Add();
         grdColors.Rows[index].Cells["Code"].Value = result[i].Code.ToString();
         grdColors.Rows[index].Cells["Desc"].Value = result[i].Desc.ToString();
    }
}

public void addrowtocolors()
{    
    for (int i = 0; i < list.Count; i++)
    {
         var index = grdColors.Rows.Add();
         grdColors.Rows[index].Cells["Code"].Value = list[i].Code.ToString();
         grdColors.Rows[index].Cells["Desc"].Value = list[i].Desc.ToString();
    }
}