Click to See Complete Forum and Search --> : Add new record to a single table


Lennie
02-01-2005, 08:04 PM
I have a data entry form, Form1, to add new record directly into the PRODUCTS table using INSERT SQL without using DataSet when the ADD Button is clicked. Or via DataSet is the only way to do it ?

The ref.book doesn't help much. Could someone pls show me how. Here is a sample of my script Thanks.


Imports System.Data
Imports System.Data.SqlClient

Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Private Sub ButtonAdd_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

Dim isql As String = "INSERT INTO Products (ProductName, UnitPrice) " & _
" VALUES (@ProductName, @UnitPrice)"

Dim adoConnect As String
adoConnect &= "Persist Security info=false;"
adoConnect &= "Integrated Security=SSPI;"
adoConnect &= "Database=OrderEntry;"

Dim adoconn As New SqlConnection(adoConnect)
Dim adoCmd As New SqlCommand(isql, adoconn)

With adoCmd
adoCmd.Parameters.Add("@ProdName", Me.txtProdDesc.Text)
adoCmd.Parameters.Add("@UnitPrice", Decimal.Parse(Me.txtUnitPrice.Text))
adoconn.Open()
End With

adoCmd.Dispose()
MsgBox("finished")

End Sub
End Class

pclement
02-02-2005, 08:35 AM
Just a cursory look at your code appears that the only statement missing would be:

adoCmd.ExecuteNonQuery()

In addition, you don't need to specify the adoCmd object in your With...End With structure:


Dim adoconn As New SqlConnection(adoConnect)
adoconn.Open()

Dim adoCmd As New SqlCommand(isql, adoconn)

With adoCmd
.Parameters.Add("@ProdName", Me.txtProdDesc.Text)
.Parameters.Add("@UnitPrice", Decimal.Parse(Me.txtUnitPrice.Text))
.ExecuteNonQuery()
End With

Lennie
02-02-2005, 03:36 PM
Thanks Paul..............yeee...haaaa.........it's working now. You are wonderful. It's people like you helping newbie like me makes this forum an awesome place to seek help. Thanks again, beers on me anytime.