用户代码未处理空引用异常。你调用的对象是空的

A Nullreferenceexception was unhandledby user code. Object Reference not set to an instance of an object

我有一个不同名称的列字段。例如,我从 ABC 加载文件。名称列字段将为 ABC。

只有当我 select ABC 行对象时我才必须显示按钮。

我在下面写了一个代码,但是它抛出了一个异常。如果有人就此建议我,那将非常有帮助。

FormViewButton fvb = FormViewButton.getInstance();

        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            row.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.SelectionBackColor;


            bool selectedRow = row.Cells["Name"].Selected;

            if (row.Cells["Name"].Value.ToString().Equals("ABC") && selectedRow == true) // A Nullreferenceexception was unhandled by user code is thrown here. 
            {
                fmv.showButton.Visible = true;
            }
            else if (!row.Cells["Name"].Value.ToString().Equals("ABC") && selectedRow != true)
            { 
                fmv.showButton.Visible = false;
            }

        }

这是因为 row.Cells["Name"]row.Cells["Name"].Value 不存在。

解决方案:当您遍历 DataGridViewRows 时,检查索引:

  • 如果RowIndex == -1那么它是header行
  • if RowIndex == dataGridView1.NewRowIndex 那么它是一个新行,单元格的 Value 将是 null

... 并检查是否 row.Cells["Name"] != null && row.Cells["Name"].Value != null,以防万一

如果单元格或字符串变量为 null 并且您尝试将某些字符串方法附加到它,例如 something.ToString() 或 something.indexof 等,C# 将始终抛出 null 异常错误.