NullReference异常错误

时间:2013-11-29 15:11:48

标签: vb.net exception-handling null

我不知道我的程序中有什么问题我的程序中的异常是cmd.commandtext,直到在model.text中

  

NullReference异常未处理对象变量或With块   变量未设置

Private Sub btnadd_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles btnadd.Click

    Dim cmd As New OleDb.OleDbCommand
    Dim tablelist As New DataTable
    If Not con.State = ConnectionState.Open Then
        con.Open()
    End If
    cmd.Connection = con

    If Me.stcode.Tag & "" = "" Then
        cmd.CommandText = "INSERT INTO Database11(stcode, description, company, department, location, user, serial number, date purchased, tagable, quantity, brand, model ) " & _
                        " VALUES(" & Me.stcode.Text & ",'" & Me.des.Text & "','" & _
                            Me.com.Text & "','" & Me.dep.Text & "','" & Me.loc.Text & "','" & _
                            Me.user.Text & "','" & Me.user.Text & "','" & Me.sn.Text & "','" & _
                            Me.dp.Text & "','" & Me.Tag.Text & "','" & Me.quan.Text & "','" & _
                            Me.brand.Text & "','" & Me.model.Text & "')"

        cmd = New OleDbCommand(cmd.CommandText, con)
        cmd.ExecuteNonQuery()
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

我的猜测是Tag控件的stcode属性为null(Nothing)。检查null,如下所示:

If strcode.Tag IsNot Nothing Then

End If

所以你的代码现在应该是:

If strcode.Tag IsNot Nothing Then
    If Me.stcode.Tag & "" = "" Then
        cmd.CommandText = "INSERT INTO Database11(stcode, description, company, department, location, user, serial number, date purchased, tagable, quantity, brand, model ) " & _
                    " VALUES(" & Me.stcode.Text & ",'" & Me.des.Text & "','" & _
                        Me.com.Text & "','" & Me.dep.Text & "','" & Me.loc.Text & "','" & _
                        Me.user.Text & "','" & Me.user.Text & "','" & Me.sn.Text & "','" & _
                        Me.dp.Text & "','" & Me.Tag.Text & "','" & Me.quan.Text & "','" & _
                        Me.brand.Text & "','" & Me.model.Text & "')"

        cmd = New OleDbCommand(cmd.CommandText, con)
        cmd.ExecuteNonQuery()
    End If
End If