c# - DataGridView 将列中的所有值写入列表

标签 c# winforms list datagridview

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

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

但是,这会返回一个错误。

最佳答案

对于错误:

'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

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 Reference 异常,您可以在添加之前添加一个检查,这将检查细胞的存在及其是否有值(value)。喜欢:

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/

相关文章:

c# - 如何检查我的程序是否已经在运行?

.NET 4.0 完整/客户端配置文件;有人关心吗?

python - 如何在 Python 中将列表初始化为某个值

java 保存列表<JButton>

python - 索引应该在范围内...但不是

c# - 如何连接到 .NET 框架内的 MySQL 数据库?

c# - 如何在不克隆的情况下获取子数组

c# - 图片上传 - 安全问题

c# - 将 JSON 文件从 .NET Core 批量上传/导入到 Azure Cosmos DB

c# - Winform窗体关闭事件