How to insert data from Form using sql express and visual web developer 2008


Here is a simple method to insert data dynamically from Form using sql express and visual web developer 2008.
It uses just a query as parameter then perform the insert job easily.

The example has a file upload control and text box.
we will only pick the absolute file name and content of textbox to insert them in database named "test" when cilck on submit button. This code doesnt upload the file , to that look for my other blog.

Step 1 . In ur vb/ vc code page type this at top of page

Imports System.Data
Imports System.Data.SqlClient

Step 2. In aspx page make 4 controls inside update panel control a file uploader, a text box and 3rd submit button and label to show errors. like this


Step4. Write the code inside submit button click event like this

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim TheFile As String
If (AsyncFileUpload2.HasFile) Then
TheFile = Strings.LCase(Replace(System.IO.Path.GetFileName(AsyncFileUpload2.FileName), " ", "_"))
Else
Label2.Text = " No files To attach"
Exit Sub
End If

Dim mysql As String = "Insert Into test ( name, filename)" & _
"VALUES (" & _
"'" & Replace(TextBox2.Text, "'", "''") & "', " & _
"'" & Replace(TheFile, "'", "''") & "') "
If insertRecord(mysql) = False Then
Label2.Text = "Unable to insert :- " & mysql
Return
End If
End Sub

Step5 : Here is the generalize function code for insert , put it somewhere in ur vb file

Function insertRecord(ByVal mysql As String) As Boolean
' start connection to ur database
' how to create sql express database : find in my blog
Dim DBConn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\intradb.mdf;Integrated Security=True;User Instance=True")
Dim DBCmd As New SqlCommand
DBConn.Open()

Try

'Add Insert Statement
DBCmd = New SqlCommand(mysql, DBConn)
DBCmd.ExecuteNonQuery()
Label2.Text = "Inserted "

Catch exp As Exception
Label2.Text = exp.Message
insertRecord = False

End Try
'Close Database connection
'and Dispose Database objects
DBCmd.Dispose()
DBConn.Close()
DBConn = Nothing
insertRecord = True

End Function


Now u can modify the code as u want and enjoy....

Vinod Kotiya

Comments