更新数据库记录

时间:2015-10-17 04:23:31

标签: vb.net exception datagridview

在通过datagridview将数据检索到文本框后,我使用以下代码来更新数据库记录。 但这给了我一个例外,因为对象引用未设置为对象的实例。请帮忙

Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridViewUserType.CellClick
    Dim i As Integer
    i = DataGridViewUserType.CurrentRow.Index
    If i >= 0 Then
        Me.txtBoxID.Text = DataGridViewUserType.Item(0, i).Value
        Me.txtBoxUserType.Text = DataGridViewUserType.Item(1, i).Value
    Else
        MessageBox.Show("Empty Row Clicked")
    End If
End Sub

Private Sub btnUserTypeUpdate_Click(sender As Object, e As EventArgs) Handles btnUserTypeUpdate.Click
    Try
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "UPDATE dbo.User_Type SET Type = @tp WHERE  Type_ID = @ID"
        cmd.Parameters.AddWithValue("@ID", txtBoxID.Text)
        cmd.Parameters.AddWithValue("@tp", txtBoxUserType.Text)
        cmd.ExecuteNonQuery()
        MessageBox.Show("Successfully Updated")
    Catch ex As Exception
        MessageBox.Show("Error while inserting record on table..." & ex.Message, "Update Records")
    Finally
        con.Close()
        btnUserTypeSave.Show()
        txtBoxID.Clear()
        txtBoxUserType.Clear()
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

谢谢Fabio 错误是" cmd" 我只是把Dim cmd作为SqlCommand = New SqlCommand使用它之前它现在正在运行。

感谢所有

相关问题