2017-08-09 24 views
0
'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 

我曾嘗試使用添加添加使用一個按鍵記錄編輯使用一個按鈕。我想更新並在vb.net

我寫下面的按鈕編碼。

只有更新部件的作品。爲什麼不是部分工作?

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 
+0

你需要做的第一件事就是閱讀有關SQL注入和參數查詢。 –

+0

您的Textbox1文本長度始終大於零,無論其更新或保存。所以檢查按鈕文字... – PRABA

+0

不要忘記看看SQL注入。 –

回答

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