Conversion failed when converting the varchar value 'table' to data type int - asp.net

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

Related

Getting id of last inserted row

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

Stored Procedure brings 0 only with ASP

I'm having a problem with an ASP 2005 application, the problem is that I´m calling a stored procedure in Oracle saved on a package, that procedure is very heavy (has like 1000 lines) and at the end it inserts into a table the data that it just calcutaded, then in other vb function I get the information from that table and show it on a gridview, but the 2 columns that are calculated sometimes come with value 0 and sometimes come with the values that should be. This only happens when I call the precedure from asp, when I run it from Toad it always get values on those columns... Do you have an idea of what could be happening??
This is the function I use for sending parameters:
Private Function LoadTable(ByVal tipee As String, ByVal period As String, ByRef ErrorUser As String, ByVal dateInit As String, ByVal dateEnd As String) As Boolean
Dim cmd As New OracleCommand
cmd.CommandText = "Schema.PKG.procedureA"
cmd.CommandType = CommandType.StoredProcedure
Dim Prmts(6) As OracleClient.OracleParameter
Prmts(0) = New System.Data.OracleClient.OracleParameter("ptipotrans", OracleType.VarChar)
Prmts(0).Value = tipee
Prmts(1) = New System.Data.OracleClient.OracleParameter("pperiodo", OracleType.VarChar)
Prmts(1).Value = period
Prmts(2) = New System.Data.OracleClient.OracleParameter("pfechaini", OracleType.VarChar)
If dateInit = "" Then
Prmts(2).Value = DBNull.Value
Else
Prmts(2).Value = dateInit
End If
Prmts(3) = New System.Data.OracleClient.OracleParameter("pfechafin", OracleType.VarChar)
If dateEnd = "" Then
Prmts(3).Value = DBNull.Value
Else
Prmts(3).Value = dateEnd
End If
Prmts(4) = New System.Data.OracleClient.OracleParameter("perror", OracleType.VarChar, 100)
Prmts(4).Direction = ParameterDirection.Output
cmd.Parameters.Clear()
For i As Integer = 0 To 4
cmd.Parameters.Add(Prmts(i))
Next
Dim cls_sql As New cls_ejecutaSql
Return cls_sql.exec_ens(cmd, errorUser)
End Function
And this the function I use for connecting to Oracle:
Public Function exec_ens(ByVal cmd As OracleCommand, ByRef msg As String) As Boolean
Dim lint_resul As Boolean
con.Open()
cmd.Connection = con
Try
cmd.ExecuteNonQuery()
lint_resul = True
Catch ex As Exception
msg = cmd.Parameters("perror").Value
lint_resul = False
Finally
con.Close()
End Try
Return lint_resul
End Function
I don't see anything out of the normal in those functions, and I also verified that the parameters are being sent well

SQL DataType Float giving/return exponationa value

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.

Validate that textbox has numeric value in vb.net and compare value with database

enter image description hereI'm trying to validate a textbox where users will put an ID. The ID has to be numeric and at the same time compare to a valid ID in the database. When I was just validating for numeric, I didn't have any problems. But now that I have two conditions, my code doesn't work properly. Whenever I type in letters in the textbox and click a button, it gives me an error. The boolean is throwing me off lol. Below is my code:
Thank you in advance.
Protected Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim dt As DataTable
Dim dr As DataRow
Dim Conn As New SqlConnection("Data Source=Computer;Initial Catalog=Catalog;Persist Security Info=True;User ID=userid;Password=password")
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value", Conn)
cmd.Parameters.Add("#Value", SqlDbType.NVarChar).Value = txtId.Text
Conn.Open()
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
Conn.Close()
If (IsNumeric(txtId.Text)) AndAlso valueExistsInDB = True AndAlso txtId.Text IsNot Nothing Then
dt = GetDataTable("SELECT ID, LEFT(SANZ_ID, PATINDEX('%.%', SANZ_ID) -1) AS City, CASE WHEN ST_DIR_ID = 1 THEN 'NB' WHEN ST_DIR_ID = 2 THEN 'SB' WHEN ST_DIR_ID = 3 THEN 'EB' WHEN ST_DIR_ID = 4 THEN 'WB' END AS ST_DIR, STREET_OF_TRAVEL, CROSS_STREET, (SELECT TOP 1 CASE WHEN STATUS_ID = 1 THEN 'F' WHEN STATUS_ID = 2 THEN 'P' WHEN STATUS_ID = 3 THEN 'I' WHEN STATUS_ID = 4 THEN 'N' WHEN STATUS_ID = 5 THEN 'A' END FROM tbl where dbo.tbl.ID=ID) AS STATUS FROM tbl WHERE ID=" & txtId.Text)
dr = dt.Rows(0)
labelStreet.Text = dr("street_of_travel")
labelCrossStreet.Text = dr("cross_street")
labelCity.Text = dr("city")
labelDir.Text = dr("st_dir")
labelAda.Text = dr("STATUS")
'dropdownStatus.SelectedValue=
dropdownStatus.Visible = True
txtNotes.Visible = True
btnSave.Visible = True
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End If
End Sub
If ID is a numeric field then you should pass a numeric parameter not an NVarChar one
' First try to convert the input text to an integer '
' this should be done here before acting on the db '
Dim id As Integer
if Not Int32.TryParse(txtId.Text, id) Then
MessageBox.Show("Error, not a valid number")
return
End If
Dim cmdText = "SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value"
Using Conn = New SqlConnection(....)
Using cmd As New SqlCommand(cmdText, Conn)
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = id
Conn.Open()
Dim valueExistsInDB = CBool(CInt(cmd.ExecuteScalar()) > 0)
' At this point you don't need anymore to check if the input value'
' is numeric and your if is more simple.....'
if valueExistsInDB Then
......
... continue with your code ....
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End if
End Using
End Using

ASP.NET variable not getting assigned values

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

Resources