控件和null引用异常

时间:2014-05-27 15:14:13

标签: asp.net vb.net nullreferenceexception

我知道NullReferenceException几乎相当于汽车上的检查引擎灯,但在这个特殊情况下,我似乎无法确定为什么它不能正常工作,我从来没有真正与控件混淆,所以我对它的技术性有点不熟悉。我有什么作品,但是当我围绕它运行trycatch时,我一直得到异常。这就是我所拥有的。

Dim TypeControl As Control

TypeControl = MaterialHeader_Edit1.FindControl("cboType")

DBTable = MaterialStuff.GetMaterial(ID)

    Using DBTable

        If DBTable.Rows.Count > 0 Then

            Try
                  CType(TypeControl, DropDownList).SelectedItem.Text = (DBTable.Rows(0).Item("MaterialTypeDescription").ToString)

Catch ex As NullReferenceException

                trace.runAllErrorLogging(ex.ToString)

            End Try

        End If

2 个答案:

答案 0 :(得分:2)

NullReferenceException与“控件”没有任何关系。它只是表明您的代码在运行时它不存在时假定对象存在。例如,如果您这样做:

TypeControl = MaterialHeader_Edit1.FindControl("cboType")
CType(TypeControl, DropDownList).SelectedItem.Text = ...

然后您的代码假定 TypeControl在第二行有值。如果没有,尝试使用.SelectedItem将失败,因为TypeControlnull。所以你假设.FindControl()实际找到的东西。它没有隐含地提供这种保证。

您应该验证:

而不是做出这个假设
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Not Nothing Then
    CType(TypeControl, DropDownList).SelectedItem.Text = ...
End If

这样代码只有在可以使用的值时才会执行。您可以添加Else来处理未找到值的条件。 (显示错误?记录错误?悄悄地继续?由您决定应该如何处理这些条件。)

答案 1 :(得分:1)

这里有两个可能的问题:

1 - FindControl实际上找到了您寻求的控件吗?添加一个签入以确保您实际找到它:

Dim TypeControl As Control
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Nothing Then Debug.Writeline("Could not find control")

2 - 控件的SelectedItem也可能是Nothing,因此您可能需要在此处添加支票:

Dim ddl = CType(TypeControl, DropDownList)
If ddl.SelectedItem Is Nothing Then Debug.Writeline("Could not find selectedItem")