我想在vb.net中使用一个按钮更新和添加记录

时间:2017-08-09 05:55:07

标签: vb.net

'Adding Function
Private Sub AddCustomer()
    Try
        sql = "INSERT INTO Category(catid, caname) Values('" & TextBox1.Text & "', '" & TextBox2.Text & "')"
        ConnD()
        cmd = New MySqlCommand(sql, conn1)
        Dim i As Integer
        i = cmd.ExecuteNonQuery
        If i > 0 Then
            MsgBox("Customer Added", MsgBoxStyle.Information, "Add Customer")
        Else
            MsgBox("Failed to add customer", MsgBoxStyle.Critical, "Add Customer")

        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        conn1.Close()
    End Try
End Sub

'UpdateFunction
Private Sub UpdateCustomer()
    Try
        sql = "Update category set caname ='" & TextBox2.Text & "' where catid = '" & TextBox1.Text & "'  "
        ConnD()
        cmd = New MySqlCommand(sql, conn1)
        Dim i As Integer
        i = cmd.ExecuteNonQuery
        If i > 0 Then
            MsgBox("Customer Updated", MsgBoxStyle.Information, "Update Customer")
        Else
            MsgBox("Failed to update customer", MsgBoxStyle.Critical, "Update Customer")
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        cmd.Dispose()
        conn1.Close()
    End Try
End Sub

我尝试使用一个按钮添加编辑

我在下面编写了按钮编码。

只有更新部分有效。为什么添加部分不起作用?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Len(TextBox1.Text) > 0 Then
        UpdateCustomer()
    Else
        AddCustomer()
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

您可以在运行时更新button1文本,并根据您可以更新或添加客户的button1文本进行更新。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Button1.Text = "Update" Then
        UpdateCustomer()
    ElseIf Button1.Text = "Save"
        AddCustomer()
    End If
End Sub