我想将第 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/