vb.net上的这段代码给了我这个错误:
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。
知道为什么以及如何解决它?
Public Class Family
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
Dim clsFamily As New clsFamily
Session("Family") = clsFamily
If clsFamily Is Nothing Then
clsFamily = New clsFamily
Else
clsFamily = Session("Family")
End If
Dim eror As Integer = 0
Dim eror_message As String = "Wrong input, please try again"
If TBxPN.Text Is "" Or TBxPN.Text Is eror_message Or Regex.IsMatch(TBxPN.Text, "^[0-9 ]+$") Then
TBxPN.Text = eror_message
eror = 1
End If
If TBxOcc.Text Is "" Or TBxOcc.Text Is eror_message Or Regex.IsMatch(TBxOcc.Text, "^[0-9 ]+$") Then
TBxOcc.Text = eror_message
eror = 1
End If
If eror = 0 Then
For i = 0 To clsFamily.PersonName.Length
Dim newName As String
Dim newOccupation As String
Dim newDate As Date
Dim newGender As String
Dim newRelation As String
newName = TBxPN.Text
newOccupation = TBxOcc.Text
newDate = Calendar1.SelectedDate.ToShortDateString()
newGender = RBLGender.SelectedItem.Text
newRelation = CBLRelation.SelectedItem.Text
ReDim Preserve clsFamily.PersonName(i)
clsFamily.PersonName(i) = newName
ReDim Preserve clsFamily.Occupation(i)
clsFamily.Occupation(i) = newOccupation
ReDim Preserve clsFamily.DOB(i)
clsFamily.DOB(i) = newDate
ReDim Preserve clsFamily.Gender(i)
clsFamily.Gender(i) = newGender
ReDim Preserve clsFamily.RelationType(i)
clsFamily.RelationType(i) = newRelation
Next i
Session("Family") = clsFamily
End If
End Sub
Public Class clsFamily
Public PersonName() As String
Public RelationType() As String
Public DOB() As Date
Public Gender() As String
Public Occupation() As String
End Class
答案 0 :(得分:-1)
你的班级确实需要一个构造函数。下一个示例将1个项添加到personName数组:""。这意味着数组不再为空,因此没有NullReferenceException。
Public Class clsFamily
Public PersonName() As String
Public RelationType() As String
Public DOB() As Date
Public Gender() As String
Public Occupation() As String
Public Sub New()
PersonName = New String(0) {""}
End Sub
End Class