首页 > 解决方案 > 将datagridview的列保存在List中

问题描述

我有包含两列(id、name)的datagridview。现在我需要将列名的值添加到List<string>

 List<string> name = new List<string>();
 for (int i = 0; i < dataGridView1.Rows.Count; i++)
 {
     string w = dataGridView1.Rows[i].Cells[1].Value.ToString();
     name.Add(w);
 }

当我尝试运行该项目时,出现以下错误。

你调用的对象是空的。

如何修复我的代码?

标签: c#list

解决方案


我想如果你使用foreach会更好..

像这样的东西:

foreach (DataGridViewRow i in dataGridView1.Rows)
{
   if(i.Cells[1].Value != null){
       name.Add(i.Cells[1].Value.ToString());        
    }
   
}

推荐阅读