Make a for each using SqlDataReader vb.net - asp.net

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.

Related

VB.net Input string was not in a correct format

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.

value of type 1-dimensional array cannot be converted to string visual

In this threat help me with the each row ( Make a for each using SqlDataReader vb.net)
But when i wanna save the data ( on GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater, lot)
the varibles od the arrarys mater and lot show the error : value of type 1-dimensional array cannot be converted to string
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
RowCounter.ToString()
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
'Dim editCustQuery As String = "select Idmaterial , IdLote from s_RptInventarioSAP where idPlanta = '" & cboPlanta0.SelectedValue & "' and IdAlmacen = '" & cboAlmacen.SelectedValue & "'"
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Dim CustCommand As New SqlCommand(editCustQuery, Con34)
Dim sqladapter As SqlDataAdapter = New SqlDataAdapter(CustCommand)
Dim tableresult As New DataTable(editCustQuery)
sqladapter.Fill(tableresult)
Con34.Close()
For Each TableRow As DataRow In tableresult.Rows
mater = tableresult.Rows.Item(RowCounter).Item(0)
planta = tableresult.Rows.Item(RowCounter).Item(1)
almacen = tableresult.Rows.Item(RowCounter).Item(2)
lot = tableresult.Rows.Item(RowCounter).Item(3)
cantidad = tableresult.Rows.Item(RowCounter).Item(4)
cantadiat = tableresult.Rows.Item(RowCounter).Item(5)
undad = tableresult.Rows.Item(RowCounter).Item(6)
Cantidadc = tableresult.Rows.Item(RowCounter).Item(7)
CantidadB = tableresult.Rows.Item(RowCounter).Item(8)
Session1 = tableresult.Rows.Item(RowCounter).Item(9)
fecha = tableresult.Rows.Item(RowCounter).Item(10)
RowCounter = RowCounter + 1
Next
Dim resultado As String
resultado = GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater, lot)
'i = i + 1
With lbError0
.Visible = True
.Text = resultado
End With
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
Ok I see a couple errors.
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 resultado() As String
Dim RowCounter As Integer = 0
Dim Con34 As New Data.SqlClient.SqlConnection
Con34.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
'Dim editCustQuery As String = "select Idmaterial , IdLote from s_RptInventarioSAP where idPlanta = '" & cboPlanta0.SelectedValue & "' and IdAlmacen = '" & cboAlmacen.SelectedValue & "'"
Dim editCustQuery As String = "select * from dbo.s_RptInventarioSAP"
Con34.Open()
Dim CustCommand As New SqlCommand(editCustQuery, Con34)
Dim sqladapter As SqlDataAdapter = New SqlDataAdapter(CustCommand)
Dim tableresult As New DataTable(editCustQuery)
sqladapter.Fill(tableresult)
Con34.Close()
For Each TableRow As DataRow In tableresult.Rows
mater(RowCounter) = tableresult.Rows.Item(RowCounter).Item(0).toString
planta(RowCounter) = tableresult.Rows.Item(RowCounter).Item(1).toString
almacen(RowCounter) = tableresult.Rows.Item(RowCounter).Item(2).toString
lot(RowCounter) = tableresult.Rows.Item(RowCounter).Item(3).toString
cantidad(RowCounter) = tableresult.Rows.Item(RowCounter).Item(4).toString
cantadiat(RowCounter) = tableresult.Rows.Item(RowCounter).Item(5).toString
undad(RowCounter) = tableresult.Rows.Item(RowCounter).Item(6).toString
Cantidadc(RowCounter) = tableresult.Rows.Item(RowCounter).Item(7).toString
CantidadB(RowCounter) = tableresult.Rows.Item(RowCounter).Item(8).toString
Session1(RowCounter) = tableresult.Rows.Item(RowCounter).Item(9).toString
fecha(RowCounter) = tableresult.Rows.Item(RowCounter).Item(10).toString
resultado(RowCounter) = GM.AsigDupla(Txtfecha.Text, cboPlanta0.SelectedValue, cboPlanta0.SelectedItem.Text, cboAlmacen.SelectedValue, cboAlmacen.SelectedItem.Text, mater(RowCounter), lot(RowCounter))
RowCounter = RowCounter + 1
Next
'i = i + 1
With lbError0
.Visible = True
.Text = resultado
End With
Catch ex As Exception
lbError0.Text = ex.Message
End Try
End If
End Sub
Ok this should work but there is something I don't understand you are displaying the result in a textbox I presume. but here is the trick. As I answer on the previous thread, the variable mater and lot are arrays, you can not call mater or lot directly. You have to specify what item of the array. With the modifications I did, resultado is another array so you can not call it directly you have to specify the item resultado().
I need more information what you will do with resultado.
For Each TableRow3 In tableresult3.Rows
mater3 = tableresult3.Rows.Item(RowCounter3).Item(0).ToString
lote3 = tableresult3.Rows.Item(RowCounter3).Item(1).ToString
Dim Con5 As New Data.SqlClient.SqlConnection
Dim StrSQL4 As String
Con5.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
StrSQL4 = "EXEC P_AsigDupla2 '" & Txtfecha.Text & "', '" & cboPlanta0.SelectedValue & "', '" & cboPlanta0.SelectedItem.Text & "', '" & cboAlmacen.SelectedValue & "', '" & cboAlmacen.SelectedItem.Text & "', '" & mater3 & "', '" & lote3 & "', '" & tbDupla.Text.ToUpper & "','" & estatus & "'"
Con5.Open()
Dim CmdAd As New Data.SqlClient.SqlCommand(StrSQL4, Con5)
CmdAd.ExecuteNonQuery()
Con5.Close()
RowCounter3 = RowCounter3 + 1

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

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

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

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