我想将第2列中的所有值写入列表:

List<string> list = new List<string>();
foreach (var item in dataGridView1.Rows)
{
    list.Add(item.Cells[1].Value.ToString);
}


但是,这将返回错误。

最佳答案

对于错误:


  'obejct'不包含'cells'的定义,也没有扩展名
  接受类型为“ object”的第一个参数的方法“ Cells”可能是
  找到(您是否缺少using指令或程序集引用?)。


您需要修改foreach循环,而不是var指定DataGridViewRow

foreach (DataGridViewRow  item in dataGridView1.Rows)
{
    list.Add(item.Cells[1].Value.ToString());
}


另外,您还需要()作为ToString

如果要使用LINQ,则可以在单个语句中执行以下操作:

List<string> list = dataGridView1.Rows
                             .OfType<DataGridViewRow>()
                             .Select(r => r.Cells[1].Value.ToString())
                             .ToList();


编辑:

如果任何行的Cell[1]的值为null,以上内容可能会导致Null引用异常,您可以在添加之前添加检查,以检查单元格的存在以及是否具有值。喜欢:

List<string> list = new List<string>();
foreach (DataGridViewRow item in dataGridView1.Rows)
{
    if (item.Cells.Count >= 2 && //atleast two columns
        item.Cells[1].Value != null) //value is not null
    {
        list.Add(item.Cells[1].Value.ToString());
    }
}


上面的检查将避免您在空对象上调用ToString,并且不会收到异常。

关于c# - DataGridView将所有值从列写入列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21314109/

10-11 03:30