2

I'm trying to select multiple rows from a DataGridView instead of iterating with a for-each loop.

I can select 1 item using this code:

DataGridViewRow row2 =
     (from DataGridViewRow r in dgView.Rows
     where r.Cells["name"].Value.ToString().Equals("Akins Ford")select r).FirstOrDefault();

But when I try to select multiple rows, using this code:

List<DataGridViewRow> rows2 =
      (from DataGridViewRow r in dgView.Rows
       where r.Cells["status"].Value.ToString().Equals("active")select r);

I got an error:

Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) C:\Software\Json\Json\Form1.cs 188 18 Json

3
  • Could you try, instead of .FirstOrDefault() try .ToList()? Commented Mar 7, 2016 at 1:46
  • I get Object reference not set to an instance of an object. error Commented Mar 7, 2016 at 1:57
  • Could you try this.... dataGridView1.Rows.Cast<DataGridViewRow>().Where(x => x.Cells["status"].Value.ToString() == "active").ToList().ForEach(x => x.Selected = true); Commented Mar 7, 2016 at 2:42

1 Answer 1

4

You need to do a simple wrap around the result:

List<DataGridViewRow> rows2 =
        new List<DataGridViewRow>
        (from DataGridViewRow r in dgView.Rows
         where r.Cells["status"].Value.ToString().Equals("active")
         select r);

This is because the linq code returns an IEnumerable<T> and not List<T>. But you can create a List<T> from an IEnumerable<T> by calling the appropriate constructor:

var list = new List<T>(iEnumerable);

To prevent null reference exceptions you might want to further improve your code thus:

List<DataGridViewRow> rows2 =
        new List<DataGridViewRow>
        (from DataGridViewRow r in dgView.Rows
         where r.Cells["status"]?.Value.ToString().Equals("active")??false
         select r);

I am assuming that you are using VS2015 which allows null propagation

r.Cells["status"]?.Value.ToString().Equals("active")??false

putting the '?' after the Cells["status"] ensures that any null references result in a null. And then the final ??false says, that if we had a null we return false (ie don't include this row).

Sign up to request clarification or add additional context in comments.

4 Comments

or just use ToList
The code compiles, but I get the following error: Object reference not set to an instance of an object.
You probably have an exception inside the where clause. Is it possible that the Cell's value can be null?
Yes, I do have a row that can be null - that fixed it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.