bbesase
bbesase

Reputation: 861

Controls and null reference exception

I'm aware that the NullReferenceException is pretty much the equivalent to the check engine light on a car but with this particular case I can't seem to pinpoint why its not working properly, I've never really messed with controls so I'm a bit unfamiliar in with the technicalities of it. What I have works, but I keep getting the exception when I run a trycatch around it. Here is what I have.

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

Upvotes: 1

Views: 341

Answers (2)

Matt Wilko
Matt Wilko

Reputation: 27322

There are two possible problems here:

1 - Does FindControl actually find the control you seek? Add a check in to make sure you are actually finding it:

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

2 - The SelectedItem of the control could also be Nothing so you may need to add a check here:

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

Upvotes: 1

David
David

Reputation: 218808

A NullReferenceException doesn't have anything to do with "controls" specifically. It's just an indication that your code assumes an object exists when at runtime it doesn't exist. For example, if you do this:

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

Then your code assumes that TypeControl has a value on the second line. If it doesn't, trying to use .SelectedItem will fail because TypeControl is null. So you're assuming that .FindControl() actually found something. It doesn't make that guarantee implicitly.

Instead of making this assumption, you should verify:

TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Not Nothing Then
    CType(TypeControl, DropDownList).SelectedItem.Text = ...
End If

That way the code only executes if there's a value that it can use. You can add an Else to handle the condition where no value is found. (Display an error? Log the error? Silently continue? It's up to you how the condition should be handled.)

Upvotes: 2

Related Questions