How To Insert Data In VB.Net


Hello friends, in this post I will discuss about storing data into a database without using a textbox to fill all data, but only using DataGridView and one button in Visual Studio 2010.

Okay, and here I have a database called "tes" and a table named "pegawai" using SQL Server 2008.

Then create a Module to make a connection and declare the global variables needed

Imports System.Data.SqlClient
Module koneksi
     Public conn As SqlConnection
     Public da As SqlDataAdapater
     Public ds As New DataSet
     Public cmd As SqlCommand
     Public build As SqlCommandBuilder

     Sub koneksinya()
       Dim str As String = "Data Source=ndiappink-pc\sqlexpress;Initial Catalog=tes;Integrated Security=True"   
       conn = New SqlConnection(str)
       If conn.State = Connection.Closed Then
       End If
     End Sub
End Module

If you need help on how to make a connection with SQL Server, read the article below

Next we open Form1 and add DataGridView and Button as shown below

Then, double-click Form1 (Sorry, my project is Form2: D) and enter the following code to display the data in the "pegawai" table into the DataGridView

Imports System.Data.SqlClient
Public Class Form1

     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 Call koneksinya()
 da = New SqlDataAdapter("select kode as KODE, nama as NAMA, alamat as ALAMAT, hp as TEEPON, jabatan as JABATAN from pegawai", conn)   
 ds = New DataSet
 DataGridView.DataSource = ds.Tables(0)
 DataGridView.Columns("KODE").Width = 50
 DataGridView.Columns("NAMA").Width = 150
 DataGridView.Columns("ALAMAT").Width = 150
 DataGridView.Columns("TELEPON").Width = 100
 DataGridView.Columns("JABATAN").Width = 150
     End Sub

End CLass

Now, double-click Button1 and enter the following code for the data storage process in the database

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click   
     Call koneksinya()
     build = New SqlCommandBuilder(da)
     MsgBox("Data Has Been Inserted")
End Sub

When finished, the project is ready to run. So, we just need to enter data in the DataGridView then click Button1

For more details, please watch the video below

1 comment:

Powered by Blogger.