ASP.NET/VB.NET/SQL Server 2012 - Page keeps loading - asp.net

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
......

Related

ExecuteReader, Make field variable

I want to make the Data Field a variable I wrote the code as follows. The SQL works but when I try to get the returned value it returns +StrVariable+ if I remove the + then it returns Strvariable literally.
Private Function FUNCTStrSN(StrVariable As String, StrSN As String) As String
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim r As SqlDataReader
Dim sqlstring As String
sqlstring = "Select " + StrVariable + " FROM HistorySNUnit WHERE SN='" + StrSN + "'"
sqlConn = New SqlConnection(DBConnection) : sqlConn.Open() : sqlComm = New SqlCommand(sqlstring, sqlConn) : r = sqlComm.ExecuteReader()
While r.Read()
Dim DBSN As String = CStr(r("StrVariable"))
StrSN = DBSN
End While : r.Close() : sqlConn.Close()
FUNCTStrSN = StrSN
End Function
How do I retrieve the value correctly? Thank you!
Try creating the SQL Command with parameters
Private Function FUNCTStrSN(StrVariable As String, StrSN As String) As String
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim r As SqlDataReader
Dim sqlstring As String
sqlstring = "Select #variable FROM HistorySNUnit WHERE SN=#value"
sqlConn = New SqlConnection(DBConnection) : sqlConn.Open() : sqlComm = New SqlCommand(sqlstring, sqlConn)
sqlComm.Parameters.AddWithValue("#variable", StrVariable)
sqlComm.Parameters.AddWithValue("#value", StrSN)
r = sqlComm.ExecuteReader()
While r.Read()
Dim DBSN As String = CStr(r(StrVariable))
StrSN = DBSN
End While : r.Close() : sqlConn.Close()
FUNCTStrSN = StrSN
End Function

Query string not retrieving data values

Hope you guys could give me some help.
I have a asp.net web form which gets data from SQL database and displays it on webpage via product code number or product description.
Searching by description will display a list of similar products where each list will have a button with the product code when clicked will open another site with extra product information,
e.g.
13892
14589
17485
00010
08890
The problem is all the codes that start from 1 upwards will show more details, but when I click on product codes that start with 0 such as 00010, 08890 will show no data when in fact there should be data.
Any help would be appreciated.
code I have below,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Val(Request.QueryString("Stock_code")) <> 0 Then
Dim dt As DataTable = New DataTable
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & _
"AND LOC_STOCK_CODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & Val(Request.QueryString("stock_code")) & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & Val(Request.QueryString("stock_code")) & "'"
Using cmd4 As SqlCommand = New SqlCommand(strQuery4)
Dim da3 As SqlDataAdapter = New SqlDataAdapter
Dim dt4 As New DataTable
cmd4.Connection = cnn : cnn.Open()
da3.SelectCommand = cmd4
da3.Fill(dt4)
For i = 0 To dt4.Rows.Count - 1
Label8.Text = dt4.Rows(i).Item("Retail_Rest_Split")
Next
End Using
cnn.Close()
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = cnn : cnn.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
For i = 0 To dt.Rows.Count - 1
Label7.Text = dt.Rows(i).Item("Stock_Code")
Label1.Text = dt.Rows(i).Item("Notes")
Label3.Text = dt.Rows(i).Item("Retail_Price")
Label4.Text = dt.Rows(i).Item("Pack_Size")
Label5.Text = dt.Rows(i).Item("Stock_Description")
'Label8.Text = dt.Rows(i).Item("Pack_Size")
Label9.Text = dt.Rows(i).Item("Net_Weight")
Label10.Text = dt.Rows(i).Item("Gross_Weight")
GridView1.DataSource = dt
GridView1.DataBind()
Next
End Using
cnn.Close()
Dim dt3 As DataTable = New DataTable
Using cmd3 As SqlCommand = New SqlCommand(strQuery3)
Dim da2 As SqlDataAdapter = New SqlDataAdapter
cmd3.Connection = cnn : cnn.Open()
da2.SelectCommand = cmd3
da2.Fill(dt3)
End Using
For i = 0 To dt3.Rows.Count - 1
Label6.Text = dt3.Rows(i).Item("Chinese_Description")
Next
Dim cmd2 As New SqlCommand
Dim dt2 As New DataTable
Dim da As New SqlDataAdapter
With cmd2
.Connection = cnn
.CommandText = strQUery2
End With
da.SelectCommand = cmd2
da.Fill(dt2)
GridView1.DataSource = dt2
GridView1.DataBind()
End If
End Sub
You want to use a paramaterized query like this (I'm going to fold that query string to make it more readable without having to scroll horizontally):
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description],
STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as
[Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as
[Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM
dbo.STK_STOCK WHERE STKCODE = #StockCode"
Using cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#StockCode", Request.QueryString("Stock_code"))
' Do your other stuff here.
End Using
Note, that you don't want to just use string concatenation to insert your query parameter. That opens you up to SQL injection attacks.
Instead, you use a placeholder in your query like #StockCode. Then you call AddWithValue on the command to give it the value of that parameter.
You can also explicitly specify the parameter type if you need to:
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
Assuming they are all 5 digit codes, this will make sure the stock code is numeric.
Replace
Val(Request.QueryString("Stock_code"))
with
String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Will raise an exception if Request.QueryString("Stock_code") is not parsed as integer, which prevents against malicious injection.
For example:
Dim stockCode = String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & stockCode & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & "AND LOC_STOCK_CODE = '" & stockCode & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & stockCode & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & stockCode & "'"
#dwilliss has just answered the question using parameters, which is probably better than my method. Posting this anyway

How to store a value from a database as a variable with VB.net

I am trying to store DoctorId from the patient table as a variable that I can then add to an insert statement (to be inserted into the Order_pres table). I am also trying to do this with PharmacyId from the pharmacy table.
The pharmacy name displays on the dropdown, however I dont know how to store the PharmacyId, as shown below:
<asp:SqlDataSource ID="SqlPharm" runat="server" ConnectionString="<%$ ConnectionStrings:SurgeryConnectionString %>" SelectCommand="SELECT DISTINCT Pharmname FROM Pharmacy "></asp:SqlDataSource>
<asp:DropDownList ID="DropPharm" runat="server" DataSourceID="SqlPharm" DataTextField="Pharmname" DataValueField="Pharmname"></asp:DropDownList>
How I am storing my variables and adding Ids to the insert query
Protected Sub btnconfirm_Click(sender As Object, e As EventArgs) Handles btnconfirm.Click
' Dropdown for pharmacy someVariable = DropPharm.SelectedItem.Value
Dim PatientId As Integer = Session("PatientId")
Dim PharmacyId As Integer = Session("PharmacyId")
Dim MedicineId As Integer = Session("MedicineID")
Dim DateOrdered As Date
' Get DoctorId from the patient table
Dim DoctorId As Integer = "SELECT DoctorId FROM Patient "
'.Value = CInt(Session("DoctorId").ToString())
Dim query As String = String.Empty
query &= "INSERT INTO Order_pres (PatientId, PharmacyId, "
query &= " DoctorId, [Date Ordered]) "
query &= "VALUES (#PatientId,#MedicineId, #PharmacyId, #DoctorId, #DateOrdered)"
Dim sqlCs As String = ConfigurationManager.ConnectionStrings("SurgeryConnectionString").ConnectionString
Using conn As New SqlConnection(sqlCs),
comm As New SqlCommand(query, conn)
With comm.Parameters
.Add("#PatientId", SqlDbType.Int).Value = Session("PatientId")
.Add("#DoctorId", SqlDbType.Int).Value = Session("DoctorId")
.Add("#MedicineId", SqlDbType.Int).Value = Session("MedicineID")
.Add("#PharmacyId", SqlDbType.Int).Value = Session("PharmacyId")
.Add("#DateOrdered", SqlDbType.DateTime).Value = DateTime.Parse(DateOrdered)
End With
I have stored some of the sessions in the login.aspx page i.e when the user logs in:
Public Function CheckUser(username As String, password As String) As Integer
Dim cmdstring As String = "SELECT * FROM Patient Where Username=#USERNAME AND Password=#PASSWORD"
Dim found = 0
Using conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Integrated Security=True;Connect Timeout=30")
Dim cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#USERNAME", SqlDbType.NChar).Value = username
cmd.Parameters.Add("#PASSWORD", SqlDbType.NChar).Value = password
conn.Open()
Dim reader = cmd.ExecuteReader()
While reader.Read()
Session("PatientId") = CInt(reader.Item("PatientId"))
Session("Username") = CStr(reader.Item("Username"))
Session("DoctorId") = CStr(reader.Item("DoctorId"))
found = CInt(reader.Item("PatientId"))
End While
reader.Close()
End Using
Return (found)
End Function
enter code here
If I have been vague or any more information is needed a for the question is needed please let me know.
Kind regards :)

Web form to console application with timer

i have created a code in asp.net webform
now i want this code to be run in console application
but i don't know
how to invoke my timer
and where to place the code
can someone help me to convert
these code into a console application
Dim con1 As New SqlConnection(_start)
Dim sql12 As String = "SELECT Auction.AuctionID FROM Item INNER JOIN Auction ON Item.ItemID = Auction.ItemID Where Auction.Status='Valid' AND Auction.EndDate<=#endate "
Dim cmd12 As New SqlCommand(sql12, con1)
con1.Open()
cmd12.Parameters.AddWithValue("#endate", DateTime.Now)
Dim query As Integer = cmd12.ExecuteScalar
Dim sql123 As String = "UPDATE Auction SET Status ='Expired' WHERE AuctionID =#auction"
Dim cmd21 As New SqlCommand(sql123, con1)
cmd21.Parameters.AddWithValue("#auction", query)
cmd21.ExecuteNonQuery()
CalculateWinningPrice(query)
WinningBet()
timer1.Enabled = True
Public Sub CalculateWinningPrice(ByVal query As Integer)
Dim price As Integer
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (AuctionID = #auction)"
Dim cmd1 As New SqlCommand(sql1, con1)
cmd1.Parameters.AddWithValue("#auction", query)
Dim max As Double = Convert.ToDouble(cmd1.ExecuteScalar)
Dim cmd2 As New SqlCommand("SELECT MAX(BiddingPrice) AS Expr1 FROM BID WHERE (BiddingPrice <( SELECT MAX(BiddingPrice) AS Expr2 FROM BID AS BID_1 WHERE (AuctionID = #auction)))", con1)
cmd2.Parameters.AddWithValue("#auction", query)
Dim second As Double = Convert.ToDouble(cmd2.ExecuteScalar)
Dim cmd3 As New SqlCommand("SELECT BuyerID FROM BID WHERE(BiddingPrice =(SELECT MAX(BiddingPrice) AS Expr1 FROM BID AS BID_1 WHERE(AuctionID = #auction)))", con1)
cmd3.Parameters.AddWithValue("#auction", query)
Dim Buyer As Integer = Convert.ToInt32(cmd3.ExecuteScalar)
If max - second = 1 Then
price = second
Else
If max - second > 10 Then
price = second + 1
Else
If max - second > 100 Then
price = second + 10
Else
If max - second > 1000 Then
price = second + 1000
End If
End If
End If
End If
Dim cmd As New SqlCommand("INSERT INTO BID VALUES(#Date, #BiddingPrice,#Status,#AuctionID,#BuyerID,#WinningPrice)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#BiddingPrice", max)
cmd.Parameters.AddWithValue("#Status", "Won")
cmd.Parameters.AddWithValue("#AuctionID", query)
cmd.Parameters.AddWithValue("#BuyerID", Buyer)
cmd.Parameters.AddWithValue("#WinningPrice", price)
cmd.Connection = con1
cmd.ExecuteNonQuery()
End Using
End Sub
then calculate winning price
Private Sub WinningBet()
Dim Email As String
Dim auction1 As Integer = Convert.ToInt32(lblauction.Text)
Using con1 As New SqlConnection(_start)
con1.Open()
Dim sql1 As String = "SELECT TOP (1) Member.Email, BID.BidID FROM BID INNER JOIN Auction ON BID.AuctionID = Auction.AuctionID INNER JOIN Buyer ON BID.BuyerID = Buyer.BuyerID INNER JOIN Member ON Buyer.MemberID = Member.MemberID WHERE(Auction.AuctionID = #auction) and (BID.WinningPrice <>0) ORDER BY BID.BidID DESC"
Dim sqlcommand As New SqlCommand(sql1, con1)
sqlcommand.Parameters.AddWithValue("#auction", auction1)
Email = sqlcommand.ExecuteScalar()
End Using
Dim [to] As String = Email
Dim from As String = "virgoplaza11#gmail.com"
Dim password As String = ""
Dim subject As String = "BID"
Dim body As String = "Your bid has been Successfull Login to shoppingCart to Make Payment"
Dim email1 As New Thread(Sub() SendEmail1([to], from, password, subject, body))
email1.IsBackground = True
email1.Start()
End Sub
Private Sub SendEmail1(ByVal [to] As String, ByVal from As String, ByVal password As String, ByVal subject As String, ByVal body As String)
Using mm As New MailMessage(from, [to])
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential(from, password)
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
End Using
End Sub
To use the Forms timer:
Add a reference to System.Windows.Forms
Imports System.Windows.Forms
For the Web.UI timer:
Add references to System.Web and System.Web.Extensions
Imports System.Web.UI
At module level declare the new timer:
Dim timer1 As New Timer

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