3

What do I do to fix an "Object reference not set to an instance of an object" error. Which object is it referring to? code:

Private Sub dvSMasterCurrentYear_DataBound(sender As Object, e As EventArgs) Handles dvSMasterCurrentYear.DataBound
    Dim dv As DetailsView = New DetailsView
    If DetailsViewMode.Insert Then
        DirectCast(dv.FindControl("PlantYear"), TextBox).Text = GetYear()
    End If
End Sub

Get Year returns to current year, it appears in the detailsview textbox "PlantYear". I try to insert the value using the above code.

thanks for your help.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
jim davis
  • 63
  • 3

1 Answers1

4

Most likely FindControl is not actually finding the control. It would be wise to put a check in to ensure it has actually found what you intended it to find:

Private Sub dvSMasterCurrentYear_DataBound(sender As Object, e As EventArgs) Handles dvSMasterCurrentYear.DataBound
    Dim dv As DetailsView = New DetailsView
    If DetailsViewMode.Insert Then
        Dim ctl = dv.FindControl("PlantYear")
        If ctl IsNot Nothing Then
            DirectCast(dv.FindControl("PlantYear"), TextBox).Text = GetYear()
        Else
            Throw New Exception("Control was not found")
        End If        
    End If
End Sub
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • This took care of the Null Object Reference. I still can't get the value to save to the record. Here is the function I use to GetYear: Public Function GetYear() Dim thisDate As Date = Now Dim thisYear As String 'thisDate = #2/12/1969# thisYear = Year(thisDate) Return thisYear End Function – jim davis Dec 14 '15 at 18:04