【问题标题】:Trying to find "null" but can't — NullReference Exception [duplicate]试图找到“null”但找不到——NullReference 异常 [重复]
【发布时间】:2014-10-21 02:51:08
【问题描述】:

我希望它能够接受将 null 作为返回值,但是在提取不存在的数据时,我不断收到 nullexception 错误……是的,我明白这听起来如何。

基本上,如果在某一列中没有找到数据,则创建一行。

获取空错误 where 子句,因为它找不到值.... 我如何解决这个问题并允许“where”在其行不给出错误?

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();
}

【问题讨论】:

  • RGV.Rows 可能是Nothing
  • 用默认值替换空值
  • 这意味着r.Cells["firstcolumn"].ValueNothing 并且Nothing 上的ToString() 会引发异常。尝试使用RowsAdded 事件用默认值填充行。即使是一个空白字符串也可以。

标签: c# linq datagridview


【解决方案1】:

使用 FirstOrDefault() 代替 First()

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

阅读When to use .First and when to use .FirstOrDefault with LINQ?

【讨论】:

  • 仍然收到错误 where 语句有什么突出的地方吗?在到达 first() 之前,它实际上给了我一个 Null 引用
  • 我已将r.Cells["firstcolumn"].Value.ToString() 更改为(string)r.Cells["firstcolumn"].Value 你注意到了吗?
  • 感谢您的回答。您能否向我解释一下它对搜索的反应有何不同...确实有效,但是如果您知道为什么可以与我分享,以便我以后知道?提前致谢!
  • 你不能打电话给null.ToString(),因为我已经使用了替代方法;转换为字符串
【解决方案2】:

自从最初的问题发布以来已经有一段时间了,但这对我有用。我希望这对其他人有帮助。 首先检查该值是否为空。然后尝试进行强制转换并检查值

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

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 2012-12-15
    相关资源
    最近更新 更多