How to add data to database using VB.NET ? Below will be a simple code that can help you.
' import the class library
Imports System.Data.SqlClient
'Declare the connection string
Dim strConn As String = "Data Source=.\SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|\StudentDB.mdf;user instance=true;"
'declare the connection
Dim myconn As New SqlConnection(strConn)
' insert data into database
Dim insertcust As String = "insert into student (ID,name) Values (@ID,@name)"
'declare sqlcommand
Dim insert As New SqlCommand(insertcust, myconn)
'using WITH loop function to loop the data from textbox
With insert.Parameters
.Add(New SqlParameter("@ID", txtID.Text.Trim))
.Add(New SqlParameter("@name", txtname.Text.Trim))
End With
'open the connection to the database
myconn.Open()
'execute the query
insert.ExecuteNonQuery()
'close the connection
myconn.Close()
Make sure you close your connection everytime after you open it.