Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

c# - DataGridView write all values from a column to list

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...