对象引用未设置为对象的实例(VS 2010 - VB)

时间:2014-03-17 02:42:54

标签: vb.net

所以这是我的代码:

Imports MySql.Data.MySqlClient

Public Class ChartOfAccounts

Public dbCon As New MySqlConnection
Public strQuery As String
Public dbCmd As MySqlCommand
Public DR As MySqlDataReader
Public dbAda As MySqlDataAdapter
Public dbTable As DataTable
Public DS As DataSet

Private Sub updateTable()
    strQuery = "SELECT * FROM account_chart"
    Try
        dbAda = New MySqlDataAdapter(strQuery, dbCon)
        dbTable = New DataTable
        DataGridView1.AutoGenerateColumns = False
        dbAda.Fill(dbTable)
        DataGridView1.DataSource = dbTable
    Catch ex As Exception
        MsgBox("MySQL Connection Error:" & ex.Message, MsgBoxStyle.Critical, "Connection Error")
    End Try
End Sub

Private Sub btncoa_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncoa_save.Click
Dim AcctName As String
Dim AcctType As String
Dim AcctNormalSide As String
Dim AcctDescription As String
Dim rowCount As Integer
AcctName = txtcoa_name.Text
AcctType = cmbcoa_type.SelectedItem
AcctNormalSide = cmbcoa_normal.SelectedItem
AcctDescription = txtcoa_desc.Text
strQuery = "SELECT COUNT(*) FROM account_chart WHERE coa_name='" & AcctName & "'"
Try
    dbCmd = New MySqlCommand(strQuery, dbCon)
    rowCount = Convert.ToInt32(dbCmd.ExecuteScalar())
    If rowCount <> 0 Then
        MsgBox("Account name already exists!", MsgBoxStyle.Critical, "Procedure Error")
    Else
        strQuery = "INSERT INTO account_chart(coa_name, coa_type, coa_normal, coa_desc) VALUES('" & AcctName & "','" & AcctType & "','" & _
            AcctNormalSide & "','" & AcctDescription & "')"
        Try
            dbCmd = New MySqlCommand(strQuery, dbCon)
            DR = dbCmd.ExecuteReader()
            DR.Read()
            DR.Close()
        Catch ex As Exception
            MsgBox("MySQL Procedure Error:" & ex.Message, MsgBoxStyle.Critical, Procedure Error")
            DR.Close()
        End Try
        MsgBox("Information added successfully!", MsgBoxStyle.Information, "Saving to Database")
    End If
    DR.Close()
Catch ex As Exception
    MsgBox("MySQL Procedure Error:" & ex.Message, MsgBoxStyle.Critical, "Procedure Error") 'error message: object reference not set to an instance...
End Try
updateTable()
End Sub
End Class

每当我输入Else语句时,我都会收到“对象引用未设置为对象实例”的错误消息(我通过试验消息框消息找到它,以便我可以看到错误消息何时出现,当我添加一个尚不存在的帐户名时它出现了。数据被添加到数据库,但它显示另一个MsgBox(显示此错误消息的那个)。我想摆脱它,以便当我向数据库添加数据时,它只显示消息框“添加成功”而没有错误消息。为什么会出现这种错误?

0 个答案:

没有答案