【问题标题】:When I try add insert a value into a asp.net Detailsview I get a "Object reference not set to an instance of an object"当我尝试将值添加到 asp.net 详细信息视图中时,我得到一个“对象引用未设置为对象的实例”
【发布时间】:2026-01-21 16:30:02
【问题描述】:

如何修复“对象引用未设置为对象的实例”错误。它指的是哪个对象? 代码:

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 返回当前年份,它出现在 detailsview 文本框“PlantYear”中。我尝试使用上面的代码插入值。

感谢您的帮助。

【问题讨论】:

  • 您必须允许 FindControl 可以返回 null/Nothing。何时/如果这样做,该代码将引发 NRE

标签: asp.net .net vb.net detailsview


【解决方案1】:

很可能 FindControl 实际上并没有找到控件。明智的做法是检查以确保它确实找到了您想要找到的内容:

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

【讨论】:

  • 这处理了空对象引用。我仍然无法将值保存到记录中。这是我用来 GetYear 的函数: Public Function GetYear() Dim thisDate As Date = Now Dim thisYear As String 'thisDate = #2/12/1969# thisYear = Year(thisDate) Return thisYear End Function
最近更新 更多