How to Save Data in the Database Using Visual Basic 2008 and SQL Server 2005

This time, I will show you how to save data in the database using Visual Basic 2008 and SQL Server 2005 Express Edition. Using this method, the data will be saved in the database and It will also display the data that you have been saved in the database to the Datagridview. See the step by step procedure below.

Let's Begin:

Step 1. Create a database in the SQL Server 2005 Express Edition and name it "userdb". Step 2. Open Visual Basic 2008 and create a new windows form application. After that, Do the form just like this. fig 1 Step 3. Go to the code editior and declare all the classes that are needed.
Reminder: Put "using System.Data.SqlClient;" above the namespace to access sql server library.
  1.  Dim con As SqlConnection = New SqlConnection()
  2.  Dim cmd As SqlCommand
Step 4. Go back to the design view, double-click the form and establish a connection between SQL Server 2005 Express Edition and Visual Basic 2008.
  1.  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2.         con.ConnectionString = "Data Source=.\SQLEXPRESS;Database=userdb;trusted_connection=true;"
  3.     End Sub
Step 5. Create a method for saving the data in the SQL Server Database.
  1.  Private Sub SaveData(ByVal sql As String)
  2.         Try
  3.             con.Open()
  4.             If con.State = ConnectionState.Open Then
  5.                 Dim result As Integer
  6.  
  7.                  cmd = New SqlCommand
  8.                 With cmd
  9.  
  10.                     .Connection = con
  11.                     .CommandText = sql
  12.                     result = .ExecuteNonQuery
  13.                 End With
  14.                 If result > 0 Then
  15.                     MsgBox("Data has been saved in the database.")
  16.                 End If
  17.             End If
  18.         Catch ex As Exception
  19.             MsgBox(ex.Message)
  20.  
  21.         Finally
  22.             con.Close()
  23.         End Try
  24.  
  25.     End Sub
Step 6. Go back to the design view, double-click a "Save" button and call the sub procedure that you have created in the method.
  1. Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
  2.  
  3.         Dim sql As String = "INSERT INTO tbluser (NAME,UNAME,PASS,UTYPE) VALUES ('" & txtName.Text & "','" & txtUsername.Text & "','" & txtPassword.Text & "','" & cboUtype.Text & "')"
  4.         SaveData(sql)
  5.  
  6.     End Sub
For all students who need a programmer for your thesis system or anyone who needs a source code in any programming languages. You can contact me @ : Email – [email protected] Mobile No. – 09305235027 – TNT

Add new comment