I have been trying to get the last inserted id into my code but i get 11 or 12 as the returned id, if the parameter type is set to either int 32 or int64 respectively.
This is the procedure i am using
CREATE procedure [dbo].[Sophia_FND_SalesOrder_CREATE](
#contact int,
#deliveryAddress varchar(50),
#Charge float,
#GrossTotal float,
#PaymentMode varchar(50),
#organisationId int,
#userid varchar(50),
#amtpaid float,
#SalesOrderId int OUTPUT
)
as
begin
insert into Sophia_FND_SalesOrder(ContactId, deliveryAddress, Charge, GrossTotal, PaymentMode, organisationId,userid, AmountPaid)
values(#contact,#deliveryAddress, #Charge, #GrossTotal, #PaymentMode, #organisationId, #userid, #amtpaid)
SET #SalesOrderId = SCOPE_IDENTITY()
RETURN #SalesOrderId
end
This is the function i am using in my class
Public Shared Function Create_salesOrder(ByVal contact As Integer, ByVal deliveryAddress As String, ByVal Charge As Double, ByVal GrossTotal As Double, ByVal PaymentMode As String, ByVal organisationId As Integer, ByVal userid As String, ByVal amtpaid As Double) As Integer
Dim comm As DbCommand = CreateCommand17()
comm.CommandText = "Sophia_FND_SalesOrder_CREATE"
AddParameter(comm, "#contact", contact, DbType.Int64)
AddParameter(comm, "#deliveryAddress", deliveryAddress, DbType.String)
AddParameter(comm, "#Charge", Charge, DbType.Double)
AddParameter(comm, "#GrossTotal", GrossTotal, DbType.Double)
AddParameter(comm, "#PaymentMode", PaymentMode, DbType.String)
AddParameter(comm, "#organisationId", organisationId, DbType.Int64)
AddParameter(comm, "#userid", userid, DbType.String)
AddParameter(comm, "#amtpaid", amtpaid, DbType.Double)
AddParameter(comm, "#SalesOrderId", DbType.Int64, ParameterDirection.Output)
Dim id As Integer
Dim insertResult As Int32 = -1
Try
insertResult = ExecuteNonQuery6(comm)
id = Convert.ToInt64(comm.Parameters("#SalesOrderId").Value)
Catch ex As Exception
Throw ex
End Try
'Return insertResult <> -1
Return id
End Function
This is how i call it in my code behind
Dim sale_id As Integer
If IsNothing(Session("soid")) Then
sale_id = Create_salesOrder(CInt(drpcontact.SelectedValue), txtdelivery.Text, lblCharge_unformated.Text, total, drpPayMode.SelectedItem.Text, SessionWrapper.OrganisationId, SessionWrapper.LoggedInUserID, CDbl(txtpayment.Text))
If Not IsNothing(sale_id) Then
Session("soid") = sale_id
Me.MessageBoard1.MessagePanel.CssClass = "errorMessage"
Me.MessageBoard1.MessagePanel.Visible = True
Me.MessageBoard1.MessageLabel.ForeColor = Drawing.Color.Green
Me.MessageBoard1.MessageLabel.Text = "done"
FillGridview()
Else
Me.MessageBoard1.MessagePanel.CssClass = "errorMessage"
Me.MessageBoard1.MessagePanel.Visible = True
Me.MessageBoard1.MessageLabel.ForeColor = Drawing.Color.Red
Me.MessageBoard1.MessageLabel.Text = "Error Occured on creating sales"
End If
end if
I found a way that work but the syntax is entirely different and i would like to stick to my syntax. The problem should be in my class function but i cant seem to know where i did the mistake.
Whenever i run this, i either get 11 or 12 as the return id which is totally wrong
Thanks
Had to change put this in my code behind and this seems to work for me. Thanks
Dim sale_id As Integer
' Dim saleslastid As Integer
Dim salecreate_line As Boolean
If IsNothing(Session("soid")) Then
' slastid = SalesOrder_id()
' saleslastid = StringHelper_2_0.ClearDBNullError(slastid.Rows(0)("id"))
'sale_id = Create_salesOrder(CInt(drpcontact.SelectedValue), txtdelivery.Text, lblCharge_unformated.Text, total, drpPayMode.SelectedItem.Text, SessionWrapper.OrganisationId, SessionWrapper.LoggedInUserID, CDbl(txtpayment.Text))
Dim strConnString As String = ConfigurationManager.ConnectionStrings("SophiaERP_Foundation_4").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Sophia_FND_SalesOrder_CREATE"
cmd.Parameters.Add("#contact", SqlDbType.Int).Value = CInt(drpcontact.SelectedValue)
cmd.Parameters.Add("#deliveryAddress", SqlDbType.VarChar).Value = txtdelivery.Text
cmd.Parameters.Add("#Charge", SqlDbType.Float).Value = lblCharge_unformated.Text
cmd.Parameters.Add("#GrossTotal", SqlDbType.Float).Value = total
cmd.Parameters.Add("#PaymentMode", SqlDbType.VarChar).Value = drpPayMode.SelectedItem.Text
cmd.Parameters.Add("#organisationId", SqlDbType.Int).Value = SessionWrapper.OrganisationId
cmd.Parameters.Add("#userid", SqlDbType.VarChar).Value = SessionWrapper.LoggedInUserID
cmd.Parameters.Add("#amtpaid", SqlDbType.Float).Value = 0
cmd.Parameters.Add("#duration", SqlDbType.Int).Value = CInt(lblduration.Text)
cmd.Parameters.Add("#SalesOrderId", SqlDbType.Int).Direction = ParameterDirection.Output
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
sale_id = cmd.Parameters("#SalesOrderId").Value
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
end if
Related
I have a table called Mst_Stock the Columns are Stk_Qty dataType is Float and Stk_ItmNo DataType is Numeric.
When i wrote a below code to Deduct the Qty from Mst_Stock When i pass the Integer value then its ok, but when its decimal value then its goes to exponation.
Please help on this.
Below is the ASP.Net Code
Private Sub Frm_StockUpdate(ByVal LdbM_NewStkQty As Double, ByVal LdbM_ItemNo As Double)
Dim LdbM_TotalQty As Double
con.Open()
cmd = New SqlClient.SqlCommand("Select * from Mst_Stock Where Stk_ItmNo=" & LdbM_ItemNo & "", con)
dr = cmd.ExecuteReader()
If dr.HasRows Then
While dr.Read
If IsDBNull(dr("Stk_Qty")) = False Then
LdbM_TotalQty = dr("Stk_Qty")
LdbM_TotalQty = LdbM_TotalQty - LdbM_NewStkQty
Else
'LdbM_TotalQty = LdbM_TotalQty + LdbM_NewStkQty
End If
End While
End If
con.Close()
Dim LsM_Qryinsert2 As String
con.Open()
LsM_Qryinsert2 = "update Mst_Stock set Stk_Qty=#Stk_Qty Where Stk_ItmNo=" & LdbM_ItemNo & ""
cmd = New SqlClient.SqlCommand(LsM_Qryinsert2, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("Stk_Qty", LdbM_TotalQty)
cmd.ExecuteNonQuery()
con.Close()
End Sub
What problem if i use float.
Thanks
Basit.
I'm creating multiple choice question system. So far i create these 4 tables and 1 view.
The tables are tblQuestion, tblAnswer, tblQuiz, tblResult and tblResultDetail. tblQuestion is to store the questions, tblAnswer to store the answers of the question,tblResult is to record for every user that answers the quiz, and store the users answers in TblResultDetails.
Based on the code below, the data is read from view. I use 1 , 2 , 3, 4 as it is the column name of the view. I did this to randomize the answers.
Sub soalan()
conn.Open()
Dim myArr(3) As String
Dim cmd As New SqlCommand("Select * From view_Soalan Where QuestionID=#IdSoalan", conn)
cmd.Parameters.AddWithValue("#IdSoalan", Counter)
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
If dr1.Read() Then
Me.lblSoalan.Text = dr1("QuestionTxt")
Me.RadioButton1.Text = dr1("1")
myArr(0) = dr1("1")
Me.RadioButton2.Text = dr1("2")
myArr(1) = dr1("2")
Me.RadioButton3.Text = dr1("3")
myArr(2) = dr1("3")
Me.RadioButton4.Text = dr1("4")
myArr(3) = dr1("4")
Dim answerId As String
If Me.RadioButton1.Checked = True Then
answerId = dr1("1")
ElseIf Me.RadioButton2.Checked = True Then
answerId = dr1("2")
ElseIf Me.RadioButton3.Checked = True Then
answerId = dr1("3")
ElseIf Me.RadioButton4.Checked = True Then
answerId = dr1("4")
End If
'Dim jawapan As Integer = CInt(answerId)
Session("jaw") = answerId
Else
conn.Close()
Counter += 1
soalan()
End If
conn.Close()
End Sub
Sub bersih()
RadioButton1.Checked = False
RadioButton2.Checked = False
RadioButton3.Checked = False
RadioButton4.Checked = False
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
soalan()
End Sub
Sub masuk()
conn.Open()
Dim cmdGetId As New SqlCommand("Select MAX(ResultId) From TblResult", conn)
cmdGetId.ExecuteNonQuery()
Dim drBaca As SqlDataReader
drBaca = cmdGetId.ExecuteReader
While drBaca.Read
Dim maxID As Integer = drBaca(0)
Session("maximum") = maxID
End While
conn.Close()
conn.Open()
Dim cmdInsert As New SqlCommand("Insert into TblResultDetail (ResultDetail_Result_Id,ResultDetail_Answer_Id) values ('" & Session("maximum") & "','" & Session("jaw") & "')", conn)
cmdInsert.ExecuteNonQuery()
conn.Close()
End Sub
End Class
I got error
Conversion failed when converting the varchar value 'table' to data
type int.
at the cmdInsert command. I know that i cant insert the session("jaw") into table directly. So how to replace it?
In your query you are quoting integers:
... values ('" & Session("maximum") & "','"
Simply remove the quotes. Also you should user Parameters instead to prevent SQL Injection.
I.e.
Dim cmdInsert As New SqlCommand("Insert into TblResultDetail (ResultDetail_Result_Id,ResultDetail_Answer_Id) values (#max, #jaw)", conn)
cmdInsert.Parameters.AddWithValue("#max", Session("maximum"))
cmdInsert.Parameters.AddWithValue("#jaw", Session("jaw"))
I think that you have store in some of this fields a wrong value.
use this
Public Module MyExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function IsInteger(ByVal value As String) As Boolean
If String.IsNullOrEmpty(value) Then
Return False
Else
Return Integer.TryParse(value, Nothing)
End If
End Function
<System.Runtime.CompilerServices.Extension()> _
Public Function ToInteger(ByVal value As String) As Integer
If value.IsInteger() Then
Return Integer.Parse(value)
Else
Return 0
End If
End Function
End Module
and then
value.ToInteger() <-- returns 0 if it is not an integer
There is another error in your code. You should use ExecuteScalar instead of ExecuteNonQuery in the query that starts with
"Select MAX(ResultId)...."
Dim cmdGetId As New SqlCommand("Select MAX(ResultId) From TblResult", conn)
Dim maxID As Integer= cmdGetId.ExecuteScalar
Session("maximum") = maxID
ExecuteScalar is typically used when your query returns a single value.
ExecuteNonQuery is typically used for SQL statements without results (UPDATE, INSERT, etc.).
Refer this
I have developed a site in vb.net (with some help from my brother in law) and it's almost ready to roll out except I am getting an unhandled exception error on the login
screen when the page is idle for a few minutes. I am reasonably new to vb.net and not a programmer :( Any help would be really appreciated. Sorry if anything in my post is not to the site standard as this is my first post. :)
I'm not sure why this is happening. The code that is executed on login_buttonClick is:
Protected Sub LoginWizard_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles LoginWizard.FinishButtonClick
Dim oUsername As String = txtUsername.Text
Dim oPassword As String = txtPassword.Text
Dim oPath As String = Server.MapPath("App_Data/IOFR.mdb")
Dim oValid As Boolean = False
Dim oReader As System.Data.OleDb.OleDbDataReader = Nothing
Dim oConnection As System.Data.OleDb.OleDbConnection = Nothing
Dim oName As String = ""
Dim oOrg As String = ""
Dim oUserId As Integer = 0
Dim oActiveAcc As String = ""
Dim oSessionExpire As Integer = 0
Try
oConnection = New System.Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Jet OLEDB:Database Password=EdmundColin13", oPath))
oConnection.Open()
Dim ipAddress As String = Request.ServerVariables("REMOTE_ADDR")
Dim cmd As New SqlCommand
Dim oParams As New List(Of System.Data.OleDb.OleDbParameter)
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmUsername", oUsername))
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmPassowrd", oPassword))
Dim oCommand As New System.Data.OleDb.OleDbCommand("SELECT ID, [Name], Organisation, ActiveAccount, [Password] FROM Users WHERE [Username] = #pmUsername AND [Password] = #pmPassword", oConnection)
oCommand.Parameters.AddRange(oParams.ToArray)
oReader = oCommand.ExecuteReader()
If oReader.Read() Then
oValid = True
oName = oReader.GetString(oReader.GetOrdinal("Name"))
oActiveAcc = oReader.GetString(oReader.GetOrdinal("ActiveAccount"))
oOrg = oReader.GetString(oReader.GetOrdinal("Organisation"))
oPassword = oReader.GetString(oReader.GetOrdinal("Password"))
oUserId = oReader.GetInt32(oReader.GetOrdinal("ID"))
oSessionExpire = oReader.GetInt32(oReader.GetOrdinal("SessionExpire"))
End If
Catch ex As Exception
Finally
If Not oReader Is Nothing Then
If Not oReader.IsClosed Then
oReader.Close()
End If
oReader = Nothing
End If
End Try
If oValid And Not String.Equals(txtPassword.Text, oPassword) Then
oValid = False
End If
If oValid Then
If oActiveAcc = "No" Then
Response.Redirect("~/DisabledAccount.aspx")
Return
End If
Session("username") = txtUsername.Text
Session("name") = oName
Session("org") = oOrg
'Generate session id and store it in session
Dim uniquesessionid As String = Guid.NewGuid().ToString()
Session("uid") = uniquesessionid
Dim oCommandSession As New System.Data.OleDb.OleDbCommand("UPDATE Users SET SessionId = #pmid, SessionExpire = '" & DateTime.Now.AddHours(2).ToString() & "' WHERE [ID] = #pmUserid", oConnection)
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmid", uniquesessionid))
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmUserid", oUserId))
oCommandSession.ExecuteNonQuery()
Response.Redirect("~/Home.aspx?login=true")
Else
txtUsername.BorderColor = Drawing.Color.Red
txtUsername.BackColor = Drawing.Color.Red
txtPassword.BorderColor = Drawing.Color.Red
FailedLogin.Visible = True
End If
If Not oConnection Is Nothing Then
If oConnection.State = Data.ConnectionState.Open Then
oConnection.Close()
End If
End If
End Sub
Thanks All. This seams to have resolved the issue.
EnableViewStateMAC="False"
I'm going to insert data into mysql. in mysql the format is :
Device varchar
Quantity varchar
StartDate datetime
EndDate datetime
This is my code :
Public Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click
InsertDevice(txtDevice.Text.ToUpper, txtQtt.Text.ToUpper, BasicDatePicker1.DateFormat, BasicDatePicker2.DateFormat)
End Sub
Private Sub InsertDevice(ByVal strAlias As String, ByVal strQtt As String, ByVal dtStart As String, ByVal dtEnd As String)
Dim connectionString As String = "server='...'; user id='...'; password='...'; Database='...'"
Dim sqlConnection As SqlClient.SqlConnection = New SqlClient.SqlConnection(connectionString)
Dim queryString As String = "INSERT INTO device VALUES " _
& "(#Device, #Quantity, #StartDate, #EndDate) "
Dim sqlCommand As SqlClient.SqlCommand = New SqlClient.SqlCommand(queryString, sqlConnection)
sqlCommand.Parameters.Add("#Device", SqlDbType.VarChar).Value = txtDevice.Text
sqlCommand.Parameters.Add("#Quantity", SqlDbType.VarChar).Value = txtQtt.Text
sqlCommand.Parameters.Add("#StartDate", SqlDbType.Date).Value = BasicDatePicker1.DisplayType
sqlCommand.Parameters.Add("#EndDate", SqlDbType.Date).Value = Now()
Try
Dim rowsAffected As Integer = 0
sqlConnection.Open()
rowsAffected = sqlCommand.ExecuteNonQuery
sqlConnection.Close()
Catch ex As Exception
lblError.Text = ex.Message.ToString
End Try
This line looks wrong:
Parameters.Add("#StartDate", SqlDbType.Date).Value = BasicDatePicker1.DisplayType
You probably want to pass the date value there.
sqlCommand.Parameters.Add("#StartDate", SqlDbType.Date).Value = BasicDatePicker1.DisplayType
Change it to
sqlCommand.Parameters.Add("#StartDate", SqlDbType.Date).Value = BasicDatePicker1.Value
Cause you want to pass the value
Im having problem with this asp.net code.
the variables qty and itname are not getting valid values ...can anyone find out the problem ?
Imports System.Data
Imports System.Data.SqlClient
Partial Class consolidate
Inherits System.Web.UI.Page
Public lastreq_no As Int32
Protected Sub btnconsolidate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnconsolidate.Click
Dim qtypen As Integer
Dim qtypencil As Integer
Dim qtygbag As Integer
Dim qtysugar As Integer
Dim i As Integer
Dim req As Integer
Dim qty As Integer
Dim itname As String = ""
Dim sqlcon As New SqlConnection("Data Source=user-hp\sqlexpress;initial catalog=campco;integrated security=true;")
If sqlcon.State = ConnectionState.Open Then
sqlcon.Close()
End If
sqlcon.Open()
Dim str As String
str = "Select Req_no from Requirements "
Dim cmd As New SqlCommand(str, sqlcon)
Dim sdr As SqlDataReader
sdr = cmd.ExecuteReader()
sdr.Read()
lastreq_no = sdr.GetInt32(sdr.VisibleFieldCount - 1)
For i = 0 To sdr.VisibleFieldCount - 1
req = sdr.GetInt32(i)
While req > lastreq_no
Dim selcomnd1 As String
Dim selcomnd2 As String
selcomnd1 = "Select #itname=It_name from Requirements where Req_no= #req"
selcomnd2 = "Select #qty= Quantity from Requirements where Req_no= #req"
Dim sqlcomnd1 As New SqlCommand(selcomnd1, sqlcon)
Dim sqlcomnd2 As New SqlCommand(selcomnd2, sqlcon)
sqlcomnd1.Parameters.AddWithValue("#itname", itname)
sqlcomnd2.Parameters.AddWithValue("#qty", qty)
sqlcomnd1.ExecuteScalar()
sqlcomnd2.ExecuteScalar()
TextBox1.Text = itname
TextBox2.Text = qty
sqlcon.Close()
sqlcon.Open()
Select Case (itname)
Case "Pen"
qtypen += qty
lastreq_no = req
Case "Pencil"
qtypencil += qty
lastreq_no = req
Case "Gunny bag"
qtygbag += qty
lastreq_no = req
Case "Sugar"
qtysugar += qty
lastreq_no = req
End Select
End While
Next
sqlcon.Close()
If sqlcon.State = ConnectionState.Open Then
sqlcon.Close()
End If
sqlcon.Open()
Dim comm As String
comm = "Insert into Consolidate (lastr_no,qtypen,qtypencil,qtygunnybag,qtysugar)values('" + lastreq_no.ToString + "','" + qtypen.ToString + "','" + qtypencil.ToString + "','" + qtygbag.ToString + "','" + qtysugar.ToString + "')"
Dim sqlcomm As New SqlCommand(comm, sqlcon)
Dim s As String
s = sqlcomm.ExecuteNonQuery()
sqlcon.Close()
End Sub
End Class
To start with, neither scalar statement is valid. Have you attempted to run those statements in SQL Management Studio or similar program to test the statements themselves? They should be something like:
selcomnd1 = "Select It_name from Requirements where Req_no=#req"
selcomnd2 = "Select Quantity from Requirements where Req_no=#req"
And then you would assign them in this manner:
itname = CType(sqlcmnd1.ExecuteScalar(), String) ' .ToString() would probably work here as well
qty = Convert.Int32(sqlcmnd2.ExecuteScalar())
Or you could use .TryParse for the qty:
Integer.TryParse(sqlcmnd2.ExecuteScalar(), qty)
The line
sqlcomnd1.Parameters.AddWithValue("#itname", itname)
provides an input parameter with the value itname. No value has been assigned to this variable.
You need to add an output parameter: see here for how to do this.
Get output parameter value in ADO.NET