C# 用户代码未处理Nullreferenceexception。对象引用未设置为对象的实例
我有一个不同名称的列字段。例如,我从ABC加载文件。“名称”列字段将为ABC 我必须仅在选择ABC行对象时显示按钮 我在下面写了一段代码,但它引发了一个异常。如果有人向我推荐这件事,那将非常有帮助C# 用户代码未处理Nullreferenceexception。对象引用未设置为对象的实例,c#,datagridview,nullreferenceexception,C#,Datagridview,Nullreferenceexception,我有一个不同名称的列字段。例如,我从ABC加载文件。“名称”列字段将为ABC 我必须仅在选择ABC行对象时显示按钮 我在下面写了一段代码,但它引发了一个异常。如果有人向我推荐这件事,那将非常有帮助 FormViewButton fvb = FormViewButton.getInstance(); foreach (DataGridViewRow row in this.dataGridView1.Rows) { row.DefaultC
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
不存在
解决方案:当您在DataGridView的行
中迭代时,请检查索引:
- 如果
RowIndex==-1
则它是一个标题行
- 如果
RowIndex
==则为新行,单元格的值将为null
。。。并检查是否row.Cells[“Name”]!=空和行。单元格[“名称”]。值!=null
,以防万一如果单元格或字符串变量为null,并且您尝试向其附加一些字符串方法,例如something.ToString()或something.indexof等,C#将始终抛出null异常错误。相关:谢谢。它解释得很好,这对我很有效。是的。非常感谢。