DataGridView write all values from a column to list

22,142

Solution 1

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.

Solution 2

To account for Null exceptions using LINQ:

List<string> list = dataGridView1.Rows
                       .OfType<DataGridViewRow>()
                       .Where(x => x.Cells[1].Value != null)
                       .Select(x => x.Cells[1].Value.ToString())
                       .ToList();
Share:
22,142
jacobz
Author by

jacobz

Graduate Student at the Technical University of Munich (TUM)

Updated on October 16, 2020

Comments

  • jacobz
    jacobz over 3 years

    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.