View Single Post
Join Date: Jun 2007
Posts: 22
Reputation: dadelsen is an unknown quantity at this point 
Solved Threads: 5
dadelsen dadelsen is offline Offline
Newbie Poster

Re: Insert,delete,Update codings in VB.NET?

 
0
  #5
Jun 14th, 2008
In most cases you would use a dataset object to keep a copy of database data inside your program, then insert, change and delete the rows in the dataset and, when done, you would use dataadapters to write the changes from the dataset to the database. But this is too much to be solved in a forum thread. There are books available, for example David Sceppa, Programming ADO.NET.

For directly inserting and deleting data into a database (using a literal on the form to show feedback):

Insert:
  1. Private Sub btnInsertDirect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  2. Handles btnInsertDirect.Click
  3. Dim iRet As Integer
  4. Dim iNextId As Integer
  5. Dim sConnectionString As String = "server=(local);database=contacts;user=ASPNET"
  6. Dim conn As New SqlConnection(sConnectionString)
  7. Dim sSQL As String
  8.  
  9. sSQL = "INSERT INTO contacts (contactid, firstname, lastname)" & _
  10. " VALUES (@contactid, @firstname, @lastname)"
  11.  
  12. Dim cmd As New SqlCommand(sSQL, conn)
  13. iNextId = 123
  14. cmd.Parameters.Add(New SqlParameter("@contactid", 123))
  15. cmd.Parameters.Add(New SqlParameter("@firstname", txtFirstName.Text))
  16. cmd.Parameters.Add(New SqlParameter("@lastname", txtLastName.Text))
  17.  
  18. conn.Open()
  19. Try
  20. iRet = cmd.ExecuteNonQuery()
  21. litMsg.Text = String.Format("Inserted {0} records", iRet)
  22. Catch ex As System.Exception
  23. litMsg.Text = String.Format("Error: {0}", ex.ToString)
  24. Finally
  25. conn.Close()
  26. End Try
  27.  
  28. End Sub
Delete:
  1. Private Sub btnDeleteDirect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteDirect.Click
  2. Dim iRet As Integer
  3. Dim sConnectionString As String = "server=(local);database=contacts;user=ASPNET"
  4. Dim conn As New SqlConnection(sConnectionString)
  5. Dim sSQL As String
  6.  
  7. sSQL = "DELETE FROM contacts WHERE lastname = '" & txtLastName.Text & "'"
  8.  
  9. Dim cmd As New SqlCommand(sSQL, conn)
  10. conn.Open()
  11. Try
  12. iRet = cmd.ExecuteNonQuery()
  13. litMsg.Text = String.Format("Deleted {0} records", iRet)
  14. Catch ex As System.Exception
  15. litMsg.Text = String.Format("Error: {0}", ex.ToString)
  16. Finally
  17. conn.Close()
  18. End Try
  19. End Sub
Reply With Quote