0

I Want it to be able to accept having null as a return value but I keep getting nullexception errors when pulling the non-existent data... Yes I understand how that sounds.

Basically, if the data is not found in a certain column, then create a row.

Getting the null error where clause because it cannot find value.... How do I get past this problem and allow "where" to not give error at its line?

var row = RGV.Rows.Cast<DataGridViewRow>()
    .Where(r => r.Cells["firstcolumn"].Value.ToString() == please)
    .First();
if (row != null)
{
    rowIndex = row.Index;
    RGV.Rows[rowIndex].Cells[secondcolumn].Value = help;
    RGV.Refresh();
}
else
{
    RGV.Rows.Add();
    int indexNew = RGV.Rows.Count;
    RGV.Rows[indexNew].Cells["firstcolumn"].Value = please;
    RGV.Rows[indexNew].Cells["secondcolumn"].Value = help;
    RGV.Refresh();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • `RGV.Rows` may be `Nothing`? – bansi Oct 21 '14 at 03:03
  • replace nulls with default value – Rex Oct 21 '14 at 03:08
  • 1
    That means `r.Cells["firstcolumn"].Value` is `Nothing` and the `ToString()` on `Nothing` throws the exception. Try using `RowsAdded` event to fill up the row with default value. Even a blank string will do. – bansi Oct 21 '14 at 03:09

2 Answers2

0

use FirstOrDefault() instead of First()

  var row = RGV.Rows.Cast<DataGridViewRow>()
                           .Where(r => (string)r.Cells["firstcolumn"].Value == please)
                           .FirstOrDefault();

Read When to use .First and when to use .FirstOrDefault with LINQ?

Community
  • 1
  • 1
Damith
  • 62,401
  • 13
  • 102
  • 153
  • Still receiving error Is there anything about the where statement that stands out? It is actually giving me a Null reference at that point before even getting to first() – CheckItOut Oct 21 '14 at 02:59
  • I have change `r.Cells["firstcolumn"].Value.ToString()` to `(string)r.Cells["firstcolumn"].Value` have you notice that? – Damith Oct 21 '14 at 03:07
  • Thank you for the answer. Could you explain to me the difference on how it is reacting to the search... It did work, but if you know why could you please share with me so I know for later? Thanks in advance! – CheckItOut Oct 21 '14 at 03:10
  • you can't call `.ToString()` of a `null`, for that I have use alternative approach; casting to a string – Damith Oct 21 '14 at 03:13
0

It's been a while since the original question was posted but here is what worked for me. I hope this helps somebody else. Check if the value is null first. Then try do the casting and check for the value

var query = from DataGridViewRow row in dgv.Rows
            where row.Cells[CATEGORY].Value != null
            where row.Cells[CATEGORY].Value.ToString() == categoryName
            select row;
Ticus
  • 11
  • 1