在一个按钮中更新和保存数据

时间:2014-05-17 02:00:12

标签: vb.net

我希望有相同的命令按钮,用于保存和更新数据从vb.net到ms访问...如果数据仍然不存在则保存数据并在数据已经存在时更新...可以任何人请帮助我..这是我的保存命令按钮的代码,当我运行它时,错误显示如下,"您向表请求的更改未成功,因为它们会在索引,主键或关系。更改包含重复数据的字段或字段中的数据,删除索引或重新定义索引以允许重复条目,然后重试。"

Private Sub timer_save_Tick(sender As Object, e As EventArgs) Handles timer_save.Tick

    If Not Me.strip_progress.Value = Me.strip_progress.Maximum Then
        Me.strip_progress.Increment(5)
        Me.strip_progress.Visible = True
    Else
        If Me.strip_progress.Value = Me.strip_progress.Maximum Then
            Me.timer_save.Stop()
            Me.strip_progress.Value = 0

            con.Open()

            If Me.txt_locid.Tag & "" = "" Then
                access = "Insert into tbl_location(locid, locname, locadd) Values ('" & txt_locid.Text & "', '" & txt_locname.Text & "', '" & txt_locadd.Text & "')"

                cmd = New OleDbCommand(access, con)
                cmd.ExecuteReader(CommandBehavior.CloseConnection)
                'con.Close()
                MsgBox("Successfully Saved....")

                Me.menu_update.Enabled = False
                Me.menu_save.Enabled = False

                Me.txt_locid.Enabled = False
                Me.txt_locname.Enabled = False
                Me.txt_locadd.Enabled = False

                Me.strip_progress.Visible = False
            Else
                access = "UPDATE tbl_location " & _
                         " SET locid=" & Me.txt_locid.Text & _
                         ", locname='" & Me.txt_locname.Text & "'" & _
                         ", locadd='" & Me.txt_locadd.Text & "'" & _
                         " WHERE locid=" & Me.txt_locid.Tag

                cmd = New OleDbCommand(access, con)
                cmd.ExecuteReader(CommandBehavior.CloseConnection)
                'con.Close()
                MsgBox("Successfully Updated...")

                Me.menu_update.Enabled = False
                Me.menu_save.Enabled = False

                Me.txt_locname.Enabled = False
                Me.txt_locadd.Enabled = False

            End If

        End If
    End If
    con.Close()
End Sub

1 个答案:

答案 0 :(得分:1)

如果没有看到您的数据库结构,则只能假设您的locid字段是主键,并且您正在尝试为数据库中已存在的值插入一个值。

您可以将数据库自动分配给locid字段(我相信它在MS Access中称为自动编号类型),然后您可以将代码更改为不插入或更新那个价值。 e.g。

            access = "Insert into tbl_location(locname, locadd) Values ('" & txt_locname.Text & "', '" & txt_locadd.Text & "')"