DataGridView将列中的所有值写入列表 [英] DataGridView write all values from a column to list

查看:89
本文介绍了DataGridView将列中的所有值写入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to write all values from column 2 to a list:

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

但是,这会返回错误。

推荐答案

对于错误:


'obejct'不包含定义对于'单元格'而没有扩展
方法'单元格'接受类型'object'的第一个参数可能是
找到(你缺少一个using指令或程序集引用?)。

'obejct' does not contain a definition for 'cells' and no extension method 'Cells' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?).

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

You need to modify your foreach loop and instead of var specify DataGridViewRow

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

您还需要() for ToString

如果你想使用LINQ,那么你可以在一个语句中这样做: / p>

If you want to use LINQ then you can do that in a single statement like:

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

编辑:

以上可能会导致如果任何行的 Cell [1] 的值为 null ,则可以在Null引用异常中添加检查添加它将检查单元格的存在以及它是否具有价值。如:

The above could result in a Null Reference exception if the value of Cell[1] for any row is null you can add a check before adding which would check for existence of cell and whether it has value or not. like:

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 在一个null对象上,你不会得到异常。

The above check would save you from calling ToString on a null object and you will not get the exception.

这篇关于DataGridView将列中的所有值写入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆