VB Get Autonum values - vb.net

I use the first "Using" statement below to insert a row to a table called "Archives". This table has a primary key that is an autonum in an Access db. The second Using statement I use to retrieve the value for the autonum field, searching by the parameters that I just entered. While this works perfectly well, it just seems ugly. Is there a way to get the autonum field returned to me after the insert? (BTW - I have deleted some code from between these two statements so if it looks a little strange, that may be why.
Using myConn As New OleDbConnection(strConnectionString),
myInsertCommand As New OleDbCommand("INSERT INTO Archives (ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus)
VALUES (#strArchUser, #strArchUserDomain, #dteArchDate, #strArchRoot, #strArchStatus);", myConn)
myInsertCommand.Parameters.Add("#strArchUser", OleDbType.VarChar, 100).Value = strArchUser
myInsertCommand.Parameters.Add("#strArchDomain", OleDbType.VarChar, 100).Value = strArchDomain
myInsertCommand.Parameters.Add("#dteArchDate", OleDbType.Date, 20).Value = dteArchDate
myInsertCommand.Parameters.Add("#strArchRoot", OleDbType.VarChar, 255).Value = strArchRoot
myInsertCommand.Parameters.Add("#strArchStatus", OleDbType.VarChar, 100).Value = strArchStatus
myConn.Open()
myInsertCommand.ExecuteNonQuery()
End Using
Dim sql As String = "SELECT ArchID
FROM Archives
WHERE ArchUserName = #ArchUserName
AND ArchUserDomain = #ArchUserDomain
AND ArchDate = #ArchDate
AND ArchRoot = #ArchRoot"
Using myConn As New OleDbConnection(strConnectionString),
command As New OleDbCommand(sql, myConn)
With command.Parameters
.Add("#ArchUserName", OleDbType.VarChar, 50).Value = strArchUser
.Add("#ArchUserDomain", OleDbType.VarChar, 50).Value = strArchDomain
.Add("#ArchDate", OleDbType.Date).Value = dteArchDate
.Add("#ArchRoot", OleDbType.VarChar, 50).Value = strArchRoot
End With
myConn.Open()
strArchID = "Arch" & CStr(command.ExecuteScalar())
strDirectoryName = "Archive" & CStr(command.ExecuteScalar())
ReturnCode = 0
End Using

Use ##Identity on the same connection immediately after the insert.
Private Function InsertArchiveRetrieveID(strArchUser As String, strArchDomain As String, dteArchDate As Date, strArchRoot As String, strArchStatus As String) As Integer
Dim NewID As Integer
Using myConn As New OleDbConnection(strConnectionString),
myInsertCommand As New OleDbCommand("INSERT INTO Archives (ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus)
VALUES (#strArchUser, #strArchUserDomain, #dteArchDate, #strArchRoot, #strArchStatus);", myConn)
With myInsertCommand.Parameters
.Add("#strArchUser", OleDbType.VarChar, 100).Value = strArchUser
.Add("#strArchDomain", OleDbType.VarChar, 100).Value = strArchDomain
.Add("#dteArchDate", OleDbType.Date, 20).Value = dteArchDate
.Add("#strArchRoot", OleDbType.VarChar, 255).Value = strArchRoot
.Add("#strArchStatus", OleDbType.VarChar, 100).Value = strArchStatus
End With
myConn.Open()
myInsertCommand.ExecuteNonQuery()
Using RetrieveNewIDCommand As New OleDbCommand("Select ##Identity From Archives,", myConn)
NewID = CInt(RetrieveNewIDCommand.ExecuteScalar)
End Using
End Using
Return NewID
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NewID = InsertArchiveRetrieveID(txtUser.Text, txtDomain.Text, DateTimePicker1.Value, txtRoot.Text, txtStatus.Text)
Dim strArchID = "Arch" & CStr(NewID)
Dim strDirectoryName = "Archive" & CStr(NewID)
End Sub

Related

How to use VB and SQL to add Records to a Relational Database in Access

I'm working in Visual Basic to create a forms applications as part of a college project. I've used SQL statements to read from the access database but I'm having some trouble writing to it. I'd like to hazard a guess it's due to the database having relationships between tables.
This is my first go at making something substantial, and vb is not my language of choice. Expect the code to be poor at best. If anyone has links to resources that I could use to improve I'd be immensely grateful.
Exception:
Exception thrown: 'System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
Exception location: 'commAddToStaff.ExecuteNonQuery()'
Both try statements are catching exceptions when ran. I've attempted providing data in the parameters rather than using data from a text box, but this hasn't resolved the issue.
Code:
Private Sub btnAddStaffMember_Click(sender As Object, e As EventArgs) Handles btnAddStaffMember.Click
'Dimension tblStaff Parameters
Dim AddEmployeeIDParam As New OleDb.OleDbParameter("#AddEmployeeID", txtAddEmployeeID.Text)
Dim AddForenameParam As New OleDb.OleDbParameter("#AddForename", txtAddForename.Text)
Dim AddSurnameParam As New OleDb.OleDbParameter("#AddSurname", txtAddSurname.Text)
Dim AddDOBParam As New OleDb.OleDbParameter("#AddDOB", txtAddDOB.Text)
Dim AddUserTierParam As New OleDb.OleDbParameter("#AddUserTier", txtAddUserTier.Text)
'Dimension tblContacts Parameters
Dim conContact As New OleDb.OleDbConnection("Provider=Microsoft.......")
Dim commContactCount As New OleDb.OleDbCommand("Select Count(*) FROM tblContacts", conContact)
commContactCount.Connection.Open()
Dim ContactID = commContactCount.ExecuteScalar + 1 'Calculate the contactID of the new record
commContactCount.Connection.Close() 'Close the connection
Dim AddContactIDParam As New OleDb.OleDbParameter("#AddContactID", ContactID)
Dim AddAddressParam As New OleDb.OleDbParameter("#AddAddress", txtAddAddress.Text)
Dim AddPostcodeParam As New OleDb.OleDbParameter("#AddPostcode", txtAddPostcode.Text)
Dim AddEmailParam As New OleDb.OleDbParameter("#AddEmail", txtAddEmail.Text)
Dim AddMobileNoParam As New OleDb.OleDbParameter("#AddMobileNo", txtAddMobileNumber.Text)
Dim conAddToStaff As New OleDb.OleDbConnection("Provider=Microsoft....")
Dim commAddToStaff As New OleDb.OleDbCommand("Insert Into tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)", conAddToStaff)
commAddToStaff.Parameters.Add(AddEmployeeIDParam)
commAddToStaff.Parameters.Add(AddForenameParam)
commAddToStaff.Parameters.Add(AddSurnameParam)
commAddToStaff.Parameters.Add(AddDOBParam)
commAddToStaff.Parameters.Add(AddUserTierParam)
Dim commAddToContact As New OleDb.OleDbCommand("Insert Into tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) Values (#AddContactID, #AddAddress, #AddPostcode, #AddEmail, #AddMobileNo)", conContact)
commAddToContact.Parameters.Add(AddContactIDParam)
commAddToContact.Parameters.Add(AddAddressParam)
commAddToContact.Parameters.Add(AddPostcodeParam)
commAddToContact.Parameters.Add(AddEmailParam)
commAddToContact.Parameters.Add(AddMobileNoParam)
Try
commAddToStaff.Connection.Open() 'Open a connection to the database
commAddToStaff.ExecuteNonQuery() 'Execute the command
commAddToStaff.Connection.Dispose() 'Remove unmanaged resources
commAddToStaff.Connection.Close() 'Close the connection
Catch ex As Exception
MessageBox.Show("Error with staff")
End Try
Try
commAddToContact.Connection.Open() 'Open a connection to the database
commAddToContact.ExecuteNonQuery() 'Execute the command
commAddToContact.Connection.Dispose() 'Remove unmanaged resources
commAddToContact.Connection.Close() 'Close the connection
Catch ex As Exception
MessageBox.Show("Error with contacts")
End Try
MessageBox.Show("Reached")
Me.Hide() 'Close the Current screen
StaffDB_Add_Staff_Security_Question.Show() 'Open the Add Security Question Screen
End Sub
You are inserting six values into six columns here:
Dim commAddToStaff As New OleDb.OleDbCommand("Insert Into tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)", conAddToStaff)
but you only add five parameters to the command here:
commAddToStaff.Parameters.Add(AddEmployeeIDParam)
commAddToStaff.Parameters.Add(AddForenameParam)
commAddToStaff.Parameters.Add(AddSurnameParam)
commAddToStaff.Parameters.Add(AddDOBParam)
commAddToStaff.Parameters.Add(AddUserTierParam)
Where's the parameter for the #AddContactID placeholder in the SQL code?
EDIT:
For the record, here's how I would tend to write code for that sort of task, ignoring the horrible way you're generating the ContactID value:
Using connection As New OleDbConnection("connection string here")
connection.Open()
Dim contactCount As Integer
Using contactCountCommand As New OleDbCommand("SELECT COUNT(*) FROM tblContacts", connection)
contactCount = CInt(contactCountCommand.ExecuteScalar())
End Using
Dim contactId = contactCount + 1
Using staffCommand As New OleDbCommand("INSERT INTO tblStaff (EmployeeID, Forename, Surname, DOB, User_Tier, ContactID) Values (#EmployeeID, #Forename, #Surname, #DOB, #User_Tier, #ContactID)", connection)
With staffCommand.Parameters
.Add("#EmployeeID", OleDbType.VarChar, 50).Value = txtAddEmployeeID.Text
.Add("#Forename", OleDbType.VarChar, 50).Value = txtAddForename.Text
.Add("#Surname", OleDbType.VarChar, 50).Value = txtAddSurname.Text
.Add("#DOB", OleDbType.Date).Value = CDate(txtAddDOB.Text) 'Why isn't this coming from a DateTimePicker?
.Add("#User_Tier", OleDbType.VarChar, 50).Value = txtAddUserTier.Text
.Add("#ContactID", OleDbType.Integer).Value = contactId
End With
staffCommand.ExecuteNonQuery()
End Using
Using contactCommand As New OleDbCommand("INSERT INTO tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) Values (#ContactID, #Address, #Postcode, #Email, #Mobile_Number)", connection)
With contactCommand.Parameters
.Add("#ContactID", OleDbType.Integer).Value = contactId
.Add("#Address", OleDbType.VarChar, 50).Value = txtAddAddress.Text
.Add("#Postcode", OleDbType.VarChar, 50).Value = txtAddPostcode.Text
.Add("#Email", OleDbType.VarChar, 50).Value = txtAddEmail.Text
.Add("#Mobile_Number", OleDbType.VarChar, 50).Value = txtAddMobileNumber.Text
End With
contactCommand.ExecuteNonQuery()
End Using
End Using
It would be easier to see where there are insufficient parameters added by rearranging the code into smaller pieces, where related items are near to each other. Something like:
Imports System.Data.OleDb
Public Class Form1
Dim connStr As String = "Provider=Microsoft......."
Sub AddStaffMemberToDatabase(contactId As Integer)
Dim sql = "INSERT INTO tblStaff (EmployeeID, Forename, Surname, DOB, UserTier, ContactID) VALUES (#AddEmployeeID, #AddForename, #AddSurname, #AddDOB, #AddUserTier, #AddContactID)"
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
Dim dob = DateTime.Parse(txtAddDOB.Text)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddEmployeeID", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddEmployeeID.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddForename", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddForename.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddSurname", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddSurname.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddDOB", .OleDbType = OleDbType.Date, .Value = dob})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddUserTier", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddUserTier.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddContactID", .OleDbType = OleDbType.Integer, .Value = contactId})
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Sub AddContactToDatabase(contactId As Integer)
Dim sql = "INSERT INTO tblContacts (ContactID, Address, Postcode, Email, Mobile_Number) VALUES (#AddContactID, #AddAddress, #AddPostcode, #AddEmail, #AddMobileNo)"
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddContactID", .OleDbType = OleDbType.Integer, .Value = contactId})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddAddress", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddAddress.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#txtAddPostcode", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddPostcode.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddEmail", .OleDbType = OleDbType.VarWChar, .Size = 255, .Value = txtAddEmail.Text})
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#AddMobileNo", .OleDbType = OleDbType.VarChar, .Size = 20, .Value = txtAddMobileNumber.Text})
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Sub AddStaffMember()
Dim sql = "SELECT COUNT(*) FROM tblContacts"
Dim contactID As Integer
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand(sql, conn)
conn.Open()
contactID = Convert.ToInt32(cmd.ExecuteScalar()) + 1
End Using
AddStaffMemberToDatabase(contactID)
AddContactToDatabase(contactID)
End Sub
Private Sub btnAddStaffMember_Click(sender As Object, e As EventArgs) Handles btnAddStaffMember.Click
AddStaffMember()
Me.Hide()
StaffDB_Add_Staff_Security_Question.Show() 'Open the Add Security Question Screen
End Sub
End Class
The Using statement makes sure that "unamanaged resources" are released when the code has finished with them.
Note that you will need to provide a more specific and robust way of parsing the DOB text (e.g. DateTime.TryParseExact). Also, the database types and sizes need to be edited to match the declarations in the database.

How to refresh database between Inserting and Selecting

I am trying to get data from a record in a database that has just been creating, but no data is found from it.
I've tried using different connections in the hope that it would be able to 'see' the new data, but this doesn't work and I am stuck!
Using oCmd As New OleDbCommand("Insert Into Users (FirstName, LastName, Username, `Password`, Teacher) Values (#firstName, #lastName, #username, #password, 0)", myConnection)
oCmd.Parameters.Add("#firstName", OleDbType.VarChar, 255).Value = txtFirstName.Text
oCmd.Parameters.Add("#lastNamee", OleDbType.VarChar, 255).Value = txtLastName.Text
oCmd.Parameters.Add("#username", OleDbType.VarChar, 255).Value = txtUsername.Text
oCmd.Parameters.Add("#password", OleDbType.VarChar, 255).Value = txtPassword.Text
oCmd.ExecuteNonQuery()
End Using
Dim userID As String = ""
Using ocmd As New OleDbCommand("Select * From Users Where FirstName = #firstName And LastName = #lastName", myConnection)
ocmd.Parameters.Add("#firstName", OleDbType.Char, 255).Value = txtFirstName.Text
ocmd.Parameters.Add("#lastName", OleDbType.Char, 255).Value = txtLastName.Text
Dim dataReader As OleDbDataReader = ocmd.ExecuteReader()
While dataReader.Read
userID = dr("UserID")
End While
The error that is shown is
System.InvalidOperationException: 'No data exists for the row/column.'
All I want is to get the userID of the record that has been created. Any help is appreciated.
To get the last entered ID.
Dim cmd1 As New OleDbCommand("Select ##IDENTITY", myConnection)
Dim itgID As Integer = CInt(cmd1.ExecuteScalar)

vb.net can't get database value in OR statement

i have kriteria database with column name kode which contain value kriteria 1 to kriteria 6
I want user can pick 3 to 6 value from kode and it will show in datagridview as matrix...
if user pick 6 kriteria there's no problem and it show matrix 6x6
...but if user pick less than 6 kriteria or parameters empty, it shows nothing...
this is my code
Private Sub perhitungankriteria_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each item In menuuser.ListBox2.Items
list2.Add(item)
Next
connect()
End Sub
Sub connect()
Dim adapter As OleDbDataReader
Dim cmd As OleDbCommand
cmd = New OleDbCommand("SELECT kode FROM kriteria WHERE kode=#kriteria1 OR kode=#kriteria2 OR kode=#kriteria3 OR kode=#kriteria4 OR kode=#kriteria5 OR kode=#kriteria6", konek)
cmd.Parameters.Add("#kriteria1", OleDbType.VarChar, 50).Value = list2(0)
cmd.Parameters.Add("#kriteria2", OleDbType.VarChar, 50).Value = list2(1)
cmd.Parameters.Add("#kriteria3", OleDbType.VarChar, 50).Value = list2(2)
cmd.Parameters.Add("#kriteria4", OleDbType.VarChar, 50).Value = list2(3)
cmd.Parameters.Add("#kriteria5", OleDbType.VarChar, 50).Value = list2(4)
cmd.Parameters.Add("#kriteria6", OleDbType.VarChar, 50).Value = list2(5)
adapter = cmd.ExecuteReader
DataGridView1.Columns.Clear()
While adapter.Read
list.Add(adapter("kode"))
DataGridView1.Columns.Add(adapter("kode"), adapter("kode"))
End While
i've try IN instead WHERE query in sql SELECT statement but same problems appears
Call BuildCommand from a button click after the user has made selections from the list box.
Dim list2() As String = {"kriteria1", "kriteria2", "kriteria3", "kriteria4", "kriteria5", "kriteria6"}
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.DataSource = list2
Private Sub BuildCommand()
Dim sb As New StringBuilder("SELECT kode FROM kriteria WHERE kode = ")
Dim ct As Integer = ListBox1.SelectedItems.Count
Dim cn As New OleDbConnection("Your connection string")
Dim cmd As New OleDbCommand
cmd.Parameters.Add("#kriteria1", OleDbType.VarChar, 50).Value = list2(0)
cmd.Parameters.Add("#kriteria2", OleDbType.VarChar, 50).Value = list2(1)
cmd.Parameters.Add("#kriteria3", OleDbType.VarChar, 50).Value = list2(2)
cmd.Parameters.Add("#kriteria4", OleDbType.VarChar, 50).Value = list2(3)
cmd.Parameters.Add("#kriteria5", OleDbType.VarChar, 50).Value = list2(4)
cmd.Parameters.Add("#kriteria6", OleDbType.VarChar, 50).Value = list2(5)
If ListBox1.SelectedItems.Contains(ListBox1.Items(0)) Then
sb.Append("#kriteria1 OR kode = ")
End If
If ListBox1.SelectedItems.Contains(ListBox1.Items(1)) Then
sb.Append("#kriteria2 OR kode = ")
End If
If ListBox1.SelectedItems.Contains(ListBox1.Items(2)) Then
sb.Append("#kriteria3 OR kode = ")
End If
If ListBox1.SelectedItems.Contains(ListBox1.Items(3)) Then
sb.Append("#kriteria4 OR kode = ")
End If
If ListBox1.SelectedItems.Contains(ListBox1.Items(4)) Then
sb.Append("#kriteria5 OR kode = ")
End If
If ListBox1.SelectedItems.Contains(ListBox1.Items(5)) Then
sb.Append("#kriteria6;")
End If
Dim strSQL As String = sb.ToString
If strSQL.EndsWith("= ") Then
Dim index As Integer = strSQL.LastIndexOf("O") 'last capital O
strSQL = strSQL.Remove(index)
strSQL &= ";"
End If
Debug.Print(strSQL) 'Check the immediate window
cmd.CommandText = strSQL
cmd.Connection = cn
'use your command as you wish
End Sub

Execute a stored procedure using VB.NET

This is my procedure
ALTER PROCEDURE sp_addUser
#UserName nvarchar(50),
#Prenom nvarchar(50),
#Nom nvarchar(50),
#Mail nvarchar(50),
#Password char(8),
#Addresse nvarchar(100),
#Ville nvarchar(50),
#Province nvarchar(50),
#PostalCode char(6),
#Pays nvarchar(50),
#AnimalGenre nvarchar(50),
#NomAnimal nvarchar(50),
#Race nvarchar(50)
AS
BEGIN
INSERT INTO Client
VALUES (#UserName,#Prenom,#Nom,#Mail,#Password,#Addresse,#Ville,#Province,#PostalCode,#Pays,#AnimalGenre,#NomAnimal,#Race);
END
I think this ok for the stored Procedure
Now the code to add value in Data Base
Sub sp_addUser()
Dim intRowsAff As Integer
lblErrMsg.Text = ""
lblRecsAff.Text = ""
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("sp_addUser", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#UserName", SqlDbType.VarChar, 50).Value = txtUserName.Text
cmd.Parameters.Add("#Prenom", SqlDbType.VarChar, 50).Value = txtPrenom.Text
cmd.Parameters.Add("#Nom", SqlDbType.NVarChar, 50).Value = txtNom.Text
cmd.Parameters.Add("#Mail", SqlDbType.NVarChar, 50).Value = txtMail.Text
cmd.Parameters.Add("#Password", SqlDbType.Char, 8).Value = txtPass.Text
cmd.Parameters.Add("#Addresse", SqlDbType.NVarChar, 100).Value = txtAdresse.Text
cmd.Parameters.Add("#Ville", SqlDbType.NVarChar, 50).Value = txtVille.Text
cmd.Parameters.Add("#Province", SqlDbType.NVarChar, 50).Value = txtProvince.Text
cmd.Parameters.Add("#PostalCode", SqlDbType.Char, 6).Value = txtPostal.Text
cmd.Parameters.Add("#Pays", SqlDbType.NVarChar, 50).Value = txtPays.Text
cmd.Parameters.Add("#AnimalGenre", SqlDbType.NVarChar, 50).Value = rblAnimal.Text
cmd.Parameters.Add("#NomAnimal", SqlDbType.NVarChar, 50).Value = txtAnimal.Text
cmd.Parameters.Add("#Race", SqlDbType.NVarChar, 50).Value = txtRace.Text
Try
cmd.Connection.Open()
intRowsAff = cmd.ExecuteNonQuery()
Catch ex As Exception
lblErrMsg.Text = ex.Message & ex.Source
End Try
lblRecsAff.Text = intRowsAff & " record(s) inserted"
cmd.Connection.Close()
End Sub
After I execute the method VS said that I have to much specified arguments for the procedure sp_addUser
I don't understand why this generate error!
just sync your Sp with code behind method and set parameters as sp.
Dim dt As New DataTable
Dim sqlpr1 As New List(Of SqlParameter)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "[sp_ItemPackingList]"
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = dateDate.Text.Trim()
cmd.Parameters.Add("#Thk", SqlDbType.VarChar).Value = txtPendQty.Text.Trim()
cmd.Parameters.Add("#Dia", SqlDbType.VarChar).Value = txtPendQty.Text.Trim()
Try
cmd.ExecuteNonQuery()
lblMessage.Text = "Record inserted successfully"
Catch ex As Exception
Throw ex
obj.GetDataTable("[sp_ItemPackingList]", sqlpr1)
End Try
The code and stored procedure you posted appear to be in sync.
That strongly suggests that the stored procedure in the Database is out of sync with what you expect in your code. Suggest you check what you posted is actually the stored procedure in DB.
Also Note: you should not prefix your proc with 'sp_' unless it natually resides in master.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
With con
.ConnectionString = sqlConnectionString
.Open()
End With
With cmd
.CommandText = "UpdateProcedure"
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("CName", txtCName.Text)
.Parameters(0).SqlDbType = SqlDbType.NVarChar
.Parameters.AddWithValue("CAddress",txtCAddress1.Text)
.Parameters(1).SqlDbType = SqlDbType.NVarChar
.Parameters.AddWithValue("CCity", txtCCity)
.Parameters(2).SqlDbType = SqlDbType.NVarChar
.ExecuteNonSqlQuery()
End With
Catch ex As Exception
Finally
cmd.Dispose()
con.Close()
End Try

SQL Server CE query having no effect?

I'm attempting to insert rows into a SQL Server CE database, and it's returning that 1 row is affected, there's no exception, and no syntax error in the query as far as I can see - but it's having no effect, when I look in the table from the Database Explorer.
If I run a query through VS, everything works fine. There's no connection problem as far as I can tell... what am I doing wrong here?
Here's the code, though it probably doesn't make a difference:
Using conn As New SqlCeConnection(My.Settings.DietSafetyCheckerReportsConnectionString)
conn.Open()
Using cmd As SqlCeCommand = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Reports(PatientID, PreparedBy, PreparedFor, WeightInKilos, HeightInMeters, Age, PercentBodyFat, ElbowMeasurementInCentimeters, ReportDate, Gender) " &
"VALUES(#pid, #pby, #pfor, #weight, #height, #age, #bodyfat, #elbow, #rdate, #gender);"
cmd.Parameters.Add("#pid", SqlDbType.NVarChar, 100).Value = Me.PatientID
cmd.Parameters.Add("#pby", SqlDbType.NVarChar, 100).Value = Me.PreparedBy
cmd.Parameters.Add("#pfor", SqlDbType.NVarChar, 100).Value = Me.PreparedFor
cmd.Parameters.Add("#weight", SqlDbType.Float).Value = Me.WeightInKilos
cmd.Parameters.Add("#height", SqlDbType.Float).Value = Me.HeightInMeters
cmd.Parameters.Add("#age", SqlDbType.TinyInt).Value = Me.Age
cmd.Parameters.Add("#bodyfat", SqlDbType.Float, 100).Value = Me.PercentBodyFat
cmd.Parameters.Add("#elbow", SqlDbType.TinyInt, 100).Value = Me.ElbowMeasurementInCentimeters
cmd.Parameters.Add("#rdate", SqlDbType.DateTime).Value = Me.ReportDate
cmd.Parameters.Add("#gender", SqlDbType.TinyInt, 100).Value = Me.Gender
If cmd.ExecuteNonQuery() <> 1 Then Throw New ApplicationException("Failed to insert row into databse.")
End Using
conn.Close()
End Using
(By the way, this also doesn't work:
Using da As New SqlCeDataAdapter("SELECT * FROM Reports", conn)
Dim ds As New DietSafetyCheckerReportsDataSet()
Dim dt As DietSafetyCheckerReportsDataSet.ReportsDataTable
da.Fill(ds)
dt = DirectCast(ds.Tables("Reports"), DietSafetyCheckerReportsDataSet.ReportsDataTable)
Dim dr As DietSafetyCheckerReportsDataSet.ReportsRow = dt.NewReportsRow()
dr.Age = Me.Age
dr.ElbowMeasurementInCentimeters = Me.ElbowMeasurementInCentimeters
dr.Gender = Me.Gender
dr.HeightInMeters = Me.HeightInMeters
dr.PatientID = Me.PatientID
dr.PercentBodyFat = Me.PercentBodyFat
dr.PreparedBy = Me.PreparedBy
dr.PreparedFor = Me.PreparedFor
dr.ReportDate = Me.ReportDate
dr.WeightInKilos = Me.WeightInKilos
dt.Rows.Add(dr)
da.Update(ds)
End Using
)
Look in your bin/debug folder, you probably have more copies of the same database file
My suggestion is that you turned off autocommit mode on server (which is on by default) or on connection settings, so you need to commit your transaction manually. Take a look here for more info.