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
Related
Here is a picture of error
Keep Getting error
input string was not in correct format
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
My guess is the CInt but it works in another similar application . Not sure what is going on . Here is the code
product-detail.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Partial Class HTML_Product_Detail
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("ProductID") <> "" Then
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
Dim connProduct As SqlConnection
Dim cmdProduct As SqlCommand
Dim drProduct As SqlDataReader
Dim strSQL As String = "Select * from Product Where ProductID = " & Request.QueryString("ProductID")
connProduct = New SqlConnection(strConn)
cmdProduct = New SqlCommand(strSQL, connProduct)
connProduct.Open()
drProduct = cmdProduct.ExecuteReader(CommandBehavior.CloseConnection)
'drProduct.Read()
If drProduct.Read() Then
lblProductName.Text = drProduct.Item("ProductName")
lblProductDescription.Text = drProduct.Item("ProductName")
lblPrice.Text = drProduct.Item("Price")
lblProductNo.Text = drProduct.Item("ProductNo")
imgProduct.ImageUrl = "images/product-detail/" + Trim(drProduct.Item("ProductNo")) + ".jpg"
End If
End If
End Sub
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' *** get product price
Dim dr As SqlDataReader
Dim strSQLStatement As String
Dim cmdSQL As SqlCommand
Dim strConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
strSQLStatement = "SELECT * FROM Product WHERE ProductNo = '" & lblProductNo.Text & "'"
Dim conn As New SqlConnection(strConnectionString)
conn.Open()
cmdSQL = New SqlCommand(strSQLStatement, conn)
dr = cmdSQL.ExecuteReader()
Dim decPrice As Decimal
If dr.Read() Then
decPrice = dr.Item("Price")
End If
conn.Close()
'*** get CartID
Dim strCartID As String
If HttpContext.Current.Request.Cookies("CartID") Is Nothing Then
strCartID = GetRandomCartIDUsingGUID(10)
Dim CookieTo As New HttpCookie("CartID", strCartID)
HttpContext.Current.Response.AppendCookie(CookieTo)
Else
Dim CookieBack As HttpCookie
CookieBack = HttpContext.Current.Request.Cookies("CartID")
strCartID = CookieBack.Value
End If
'Check if this product already exist in the cart
Dim dr2 As SqlDataReader
Dim strSQLStatement2 As String
Dim cmdSQL2 As SqlCommand
strSQLStatement2 = "SELECT * FROM cart WHERE CartID ='" & strCartID & "' and ProductID = '" & Trim(lblProductNo.Text) & "'"
'Reponse.Write(strSQlStatement2)
Dim conn2 As New SqlConnection(strConnectionString)
cmdSQL2 = New SqlCommand(strSQLStatement2, conn2)
conn2.Open()
dr2 = cmdSQL2.ExecuteReader()
If dr2.Read() Then
Dim intQuantityNew As Integer = dr2.Item("Quantity") + CInt(tbQuantity.Text)
strSQLStatement = ""
cmdSQL = New SqlCommand(strSQLStatement, conn)
Else
Dim dr3 As SqlDataReader
Dim strSQLStatement3 As String
Dim cmdSQL3 As SqlCommand
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
'Response.Write(strSQLStatement3)
Dim conn3 As New SqlConnection(strConnectionString)
conn3.Open()
cmdSQL3 = New SqlCommand(strSQLStatement3, conn3)
dr3 = cmdSQL3.ExecuteReader()
End If
'Response.Redirect("ViewCart.aspx")
End Sub
Public Function GetRandomCartIDUsingGUID(ByVal length As Integer) As String
'Get the GUID
Dim guidResult As String = System.Guid.NewGuid().ToString()
'Remove the hyphens
guidResult = guidResult.Replace("-", String.Empty)
'Make sure length is valid
If length <= 0 OrElse length > guidResult.Length Then
Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
End If
'Return the first length bytes
Return guidResult.Substring(0, length)
End Function
End Class
The issue is almost certainly here:
CInt(tbQuantity.Text)
The exception information even says:
Conversion from string "" to type 'Integer' is not valid.
You cannot convert a String to an Integer if the text doesn't represent a valid value and an empty string obviously doesn't represent a number. Validate the data first or else validate and convert in one go using Integer.Tryparse.
i need store the value "IdMaterial" from table 1 ( imagine that have more that 40 records) into a array save all that reacord into table 2 on the code i will show you only save me the first record and not all.
i will apreceate your help i a noobie in proraming
Code :
Dim i As Integer
i = 0
Try
Dim mater As String
Dim planta As String
Dim almacen As String
Dim lot As String
Dim cantidad As String
Dim cantadiat As String
Dim undad As String
Dim Cantidadc As String
Dim CantidadB As String
Dim Session1 As String
Dim fecha As String
'''''
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Using CustCommand As New SqlCommand(editCustQuery, Con34)
Dim dr As SqlDataReader = CustCommand.ExecuteReader()
dr.Read()
mater = dr.GetString(0)
planta = dr.GetString(1)
almacen = dr.GetString(2)
lot = dr.GetString(3)
cantidad = dr.GetString(4)
cantadiat = dr.GetString(5)
undad = dr.GetString(6)
Cantidadc = dr.GetString(7)
CantidadB = dr.GetString(8)
Session1 = dr.GetString(9)
fecha = dr.GetDateTime(10)
end using
Dim Con As New Data.SqlClient.SqlConnection
Dim StrSQL As String
Con.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
StrSQL = ""
StrSQL = "EXEC P_AsigDupla '" & Txtfecha.Text & "','" & cboPlanta0.SelectedValue & "', '" & cboPlanta0.SelectedItem.Text & "','" & cboAlmacen.SelectedValue & "', '" & cboAlmacen.SelectedItem.Text & "', '" & mater & "', '" & lot & "'"
Con.Open()
Dim CmdAd As New Data.SqlClient.SqlCommand(StrSQL, Con)
CmdAd.ExecuteNonQuery()
Con.Close()
i = i + 1
'Next
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
First of all if I understand correctly, you want to put the information of those 40 rows and multiple columns into multiple arrays. If that is true then you are missing () when declaring the arrays.
Dim mater() As String
Dim planta() As String
Dim almacen() As String
Dim lot() As String
Dim cantidad() As String
Dim cantadiat() As String
Dim undad() As String
Dim Cantidadc() As String
Dim CantidadB() As String
Dim Session1() As String
Dim fecha() As String
Dim RowCounter as Integer = 0
Second I will approach this different. I will run the query and put the result into a DataTable. Then with a For go through each row and start filling the arrays.
MySQLOpenConnection()
Dim MySQLExecute As New MySqlCommand(MySQLCommand, MySQLConnection)
Dim MySQLAdapter As MySqlDataAdapter = New MySqlDataAdapter(MySQLExecute)
Dim TableResult As New DataTable("QueryResult")
MySQLAdapter.Fill(TableResult)
MySQLCloseConnection()
For each tablerow as DataRow in TableResult.Rows
mater(RowCounter) = TableResult.Rows.Item(RowCounter).Item(0)
planta(RowCounter) = TableResult.Rows.Item(RowCounter).Item(1)
almacen(RowCounter) = TableResult.Rows.Item(RowCounter).Item(2)
lot(RowCounter) = TableResult.Rows.Item(RowCounter).Item(3)
cantidad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(4)
cantadiat(RowCounter) = TableResult.Rows.Item(RowCounter).Item(5)
undad(RowCounter) = TableResult.Rows.Item(RowCounter).Item(6)
Cantidadc(RowCounter) = TableResult.Rows.Item(RowCounter).Item(7)
CantidadB(RowCounter) = TableResult.Rows.Item(RowCounter).Item(8)
Session1(RowCounter) = TableResult.Rows.Item(RowCounter).Item(9)
fecha(RowCounter) = TableResult.Rows.Item(RowCounter).Item(10)
RowCounter=RowCounter+1
Next
The comment did not have enough characters for the answer for the second issue so here it goes.
Ok, I see you are using values from the array mater, and lot, but you have to define which one of the values inside the array.
mater() and lot() are as long as the amount of rows of the of the table in the database. So if you have 20 rows on that table, the array lot will have 20 elements going from lot(0) to lot(19) and the same for the others.
If you need to get resultado for each row, then you have to define resultado() as an array and use the same FOR to fill it.
resultado(RowCounter)=GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater(RowCounter), lot(RowCounter)
I hope this solve your issue.
I want to bind the url to GridView but I don't know how.
For example when I type the http://localhost:12345/example.aspx?FirstName=John in the url it will give me the result in GridView that shows only with the FirstName "John".
Here's my curent code:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim dt As New DataTable
' Stablish ODBC Connection
Dim con As New OdbcConnection("DRIVER={SQL Server};Server=WJNJPHR8TCX8P\SQLEXPRESS;Database=Fabrics;Integrated Security=True;")
' Query Command
Dim cmd As New OdbcCommand("SELECT * FROM [Client] WHERE [FirstName] = ?", con)
con.Open()
' Gets the path (Example.aspx)
Dim path As String = HttpContext.Current.Request.Url.AbsolutePath
' Gets the host (localhost)
Dim host As String = HttpContext.Current.Request.Url.Host
' Gets the whole url (localhost:24124/Example.aspx)
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
' Parse the query string variables into a NameValueCollection
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(url)
' Iterate through the collection and shows the result in MsgBox
Dim sb As New StringBuilder()
For Each s As String In qscoll.AllKeys
sb.Append(s & " = " & qscoll(s) & vbCrLf)
Next s
MsgBox(sb.ToString)
' Gets all keys and values in query string and shows it on MsgBox
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
Next key
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter
par1.OdbcType = OdbcType.NVarChar
par1.Value = FName
par1.ParameterName = "#FirtName"
cmd.Parameters.Add(par1)
'Shows the result in Data Grid
dt.Load(cmd.ExecuteReader()) '==> Error: Invalid use of default parameter
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Any help will do!
You can access your query string directly with
Dim firstName as string = Request.QueryString("firstName")
Then you must pass it as a parameter of the query before executing it
Dim par1 As New OdbcParameter
par1.DbType = DbType.String
par1.Value = firstName
par1.ParameterName = "#FirstName"
cmd.Parameters(1) = par1
Hope it helps
Answered my question!
Here's my code:
For Each key As String In HttpContext.Current.Request.QueryString.AllKeys
Dim FName As String = Request.QueryString("FirstName")
Dim par1 As New OdbcParameter With {
.OdbcType = OdbcType.NVarChar,
.Value = FName,
.ParameterName = "#FirstName"
}
cmd.Parameters.Add(par1)
MsgBox("Key: " + key + " Value: " + Request.QueryString(key))
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView1.DataBind()
Next key
#isol Thanks for your help! :)
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'm trying to run this code, and whenever I press the 'Register' button, nothing is happening (the page is like loading but stays on the same page)
Code:
Public Sub register()
Dim Username As String = txtUsername.Text
Dim Surname As String = txtSurname.Text
Dim Password As String = txtPassword.Text
Dim Name As String = txtName.Text
Dim Address1 As String = txtAddress1.Text
Dim Address2 As String = txtAddress2.Text
Dim City As String = txtCity.Text
Dim Email As String = txtEmail.Text
Dim Country As String = drpCountry.Text
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.Text
Dim WorkLocation As String = txtWorkLocation.Text
Dim Age As Integer = Date.Today.Year - calDOB.SelectedDate.Year
Dim ProjectManager As String = "N/A"
Dim TeamLeader As String = "N/A"
Dim TeamLeaderID As Integer = "1"
Dim ProjectManagerID As Integer = "1"
Dim RegistrationDate As Date = DateTime.Today
Dim ContractType As String = "N/A"
Dim ContractDuration As Integer = 6
Dim Department As String = "N/A"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim registerSQL As SqlCommand
Dim sqlComm As String
Dim validateSQL As SqlCommand
Dim sqlValidate As String
sqlValidate = "SELECT * FROM users where username=" + txtUsername.Text.ToString
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
"City, Country, date_of_birth, age, Occupation, department, work_location, " +
"project_manager,team_leader, team_leader_id, project_manager_id, " +
"date_registration, contract_type, contract_duration) " +
"VALUES(#p1, #p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10,#p11,#p12,#p13,#p14,#p15," +
"#p16,#p17,#p18,#p19,#p20)"
conn.Open()
validateSQL = New SqlCommand(sqlValidate, conn)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
If dr.HasRows = False Then
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.CommandText = sqlValidate
Dim reader As SqlDataReader = validateSQL.ExecuteReader()
reader.Read()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
registerSQL.Parameters.AddWithValue("#p2", Password)
registerSQL.Parameters.AddWithValue("#p3", Name)
registerSQL.Parameters.AddWithValue("#p4", Surname)
registerSQL.Parameters.AddWithValue("#p5", Address1)
registerSQL.Parameters.AddWithValue("#p6", Address2)
registerSQL.Parameters.AddWithValue("#p7", City)
registerSQL.Parameters.AddWithValue("#p8", Country)
registerSQL.Parameters.AddWithValue("#p9", DOB)
registerSQL.Parameters.AddWithValue("#p10", Age)
registerSQL.Parameters.AddWithValue("#p11", Occupation)
registerSQL.Parameters.AddWithValue("#p12", Department)
registerSQL.Parameters.AddWithValue("#p13", WorkLocation)
registerSQL.Parameters.AddWithValue("#p14", ProjectManager)
registerSQL.Parameters.AddWithValue("#p15", TeamLeader)
registerSQL.Parameters.AddWithValue("#p16", TeamLeaderID)
registerSQL.Parameters.AddWithValue("#p17", ProjectManagerID)
registerSQL.Parameters.AddWithValue("#p18", RegistrationDate)
registerSQL.Parameters.AddWithValue("#p19", ContractType)
registerSQL.Parameters.AddWithValue("#p20", ContractDuration)
registerSQL.ExecuteNonQuery()
conn.Close()
ElseIf dr.HasRows = True Then
lblUsername.Text = "That Username (" + txtUsername.Text + ") is already registered/taken."
lblUsername.Visible = True
conn.Close()
End If
End Sub
Button event handler:
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Is something wrong with the code?
From MSDN
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
It appears that you have the SqlDataReader open when you try to execute the insert command.
I will try to close it before using the insert command
If dr.HasRows = False Then
dr.Close()
' The following lines are probably a remainder of a copy/paste operation'
' They are not needed and you should remove them'
'validateSQL = New SqlCommand(sqlValidate, conn)'
'validateSQL.CommandText = sqlValidate'
'Dim reader As SqlDataReader = validateSQL.ExecuteReader()'
'reader.Read()'
' Now execute the insert command
Also your command to check for the user presence, apart from perfomance arguments, is wrong because introduces Sql Injection possibilities.
Summarizing try with these changes....
sqlValidate = "SELECT * FROM users where username=#uname"
validateSQL = New SqlCommand(sqlValidate, conn)
validateSQL.Parameters.AddWithValue("#uname", txtUserName.Text)
Dim dr As SqlDataReader = validateSQL.ExecuteReader()
Dim userFound = dr.HasRows
dr.Close()
if userFound = False then
......