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

本文关键字:添加 datagridview 列表 编程 方式 | 更新日期: 2023-09-27 18:03:31

我有程序,以编程方式将列表添加到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;
}

但是当我调用它是添加3相同的行到datagridview,在列表中我只有一个。

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

谢谢。

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

根据我的评论…我还删除了返回值,因为只返回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();
    }
}