DataGridView 将列中的所有值写入列表 [英] DataGridView write all values from a column to list
问题描述
我想将第 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);
}
然而,这会返回一个错误.
However, this returns an error.
推荐答案
对于错误:
'obejct' 不包含 'cells' 的定义,也没有扩展名方法 'Cells' 接受类型为 '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,那么你可以在一个单一的语句中做到这一点:
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 Reference 异常,您可以在添加之前添加检查单元格的存在以及它是否有价值.喜欢:
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
并且您不会得到异常.
The above check would save you from calling ToString
on a null object and you will not get the exception.
这篇关于DataGridView 将列中的所有值写入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!