For the error:
'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?).
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());
}
Also you need ()
for ToString
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();
EDIT:
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());
}
}
The above check would save you from calling ToString
on a null object and you will not get the exception.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…