Suspect code running twice or not at all sometimes, intermittent issue - asp.net

The code below is causing me some real headaches. It was written probably two years ago and has been chugging away ever since, but we've noticed that sometimes the insert query will run twice, and sometimes not at all. The code basically takes integer and decimal values from webpage (aspx) labels and inserts them into a master table.
The problem lately seems to be affected by the number of users on the system. When there is only one person using it there seems to be no issue, but with multiple users the problems start to occur. I was using session variables rather than labels but as a process of elimination i stopped using these.
If anyone can help or give me some pointers that would be great, many thanks.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
'local
Dim subidString As String = "SELECT [Submission_ID], [Week Ending] FROM tbl_Weekly_Expenses WHERE [Submission_ID] = #SubID AND [Week Ending] = #WeekEnding AND [SentToPayroll] IS NULL"
'local
Dim mtdString As String = "SELECT SUM([Mileage Covered]) AS SumOfMileageCovered FROM tbl_Weekly_Expenses WHERE [Gabem Employee Reference] = #NovaRef"
'remote
Dim vehicleString As String = "SELECT [Vehicle] FROM tblExpensesMileage WHERE [SubID] = #SubID"
'local
Dim insertString As String = "INSERT INTO tbl_Weekly_Expenses ([Week Ending], [Date Expenses Processed], [Expenses_From], [Expenses_To], [Date Expenses received], [Gabem Employee Reference], [Identifying Number], [Submission_ID], [Car], [Motorcycle], [Pushbike], [Mileage Covered], [Mileage Amount Claimed], [Accommodation], [Meal Allowance], [Daily Allowance], [Tools/Clothing], [Details_Of_Tools], [Travel Amount], [Telephone], [Professional Fees], FuelVAT, MAVAT, TAVAT, AVAT, DAVAT, TCVAT, TelVAT, PfVAT, processedby) " & _
"VALUES (#WeekEnding, #DateProcessed, #ExpensesFrom, #ExpensesTo, #DateReceived, #NovaRef, #IdentifyingNumber, #SubID, #Car, #Motorcycle, #Pushbike, #MileageCovered, #MileageAmountClaimed, #Accommodation, #Meals, #DailyAllowance, #ToolsClothing, #ToolsDetails, #Travel, #TelephoneCalls, #ProfessionalFees, #FuelVAT, #MAVAT, #TAVAT, #AVAT, #DAVAT, #TCVAT, #TelVAT, #PfVAT, #processedby)"
'remote
Dim updateMileage As String = "UPDATE tblExpensesMileage SET [Status] = 'Processed' WHERE [MileageID] = #id"
Dim updateAccommodation As String = "UPDATE tblExpensesAccommodation SET [Status] = 'Processed' WHERE [AccommodationID] = #id"
Dim updateMeals As String = "UPDATE tblExpensesMeals SET [Status] = 'Processed' WHERE [MealsID] = #id"
Dim updateLaundry As String = "UPDATE tblExpensesLaundry SET [Status] = 'Processed' WHERE [LaundryID] = #id"
Dim updateDailyAllowance As String = "UPDATE tblExpensesDailyAllowance SET [Status] = 'Processed' WHERE [DailyAllowanceID] = #id"
Dim updateTravel As String = "UPDATE tblExpensesTravel SET [Status] = 'Processed' WHERE [TravelID] = #id"
Dim updateTools As String = "UPDATE tblExpensesTools SET [Status] = 'Processed' WHERE [ToolsID] = #id"
Dim updateTelephoneCalls As String = "UPDATE tblExpensesTelephoneCalls SET [Status] = 'Processed' WHERE [TelephoneCallsID] = #id"
Dim updateProfessionalFees As String = "UPDATE tblExpensesProfessionalFees SET [Status] = 'Processed' WHERE [ProfessionalFeesID] = #id"
Dim dbconnLocal As String = ConfigurationManager.ConnectionStrings("connection_nbsas2").ConnectionString
Dim dbconnRemote As String = ConfigurationManager.ConnectionStrings("connection_nbsa_web").ConnectionString
If txtWEDate.Text = String.Empty Then
Exit Sub
End If
Using myConnectionLocal As New SqlConnection(dbconnLocal)
myConnectionLocal.Open()
'VEHICLE TYPE AND PPM STARTS
Dim Car As Integer = 0
Dim Motorcycle As Integer = 0
Dim Pushbike As Integer = 0
Dim ppm As Decimal
Using myConnectionRemote As New SqlConnection(dbconnRemote)
myConnectionRemote.Open()
'Vehicle type
Dim cmdSelectVehicle As New SqlCommand(vehicleString, myConnectionRemote)
cmdSelectVehicle.Parameters.AddWithValue("#SubID", Session("subid"))
Dim readerVehicle As SqlDataReader = cmdSelectVehicle.ExecuteReader()
readerVehicle.Read()
If readerVehicle.HasRows = True Then
'MTD value for pence per mile (ppm)
Dim cmdSelectMTD As New SqlCommand(mtdString, myConnectionLocal)
cmdSelectMTD.Parameters.AddWithValue("#NovaRef", Session("novaref"))
Dim readerMTD As SqlDataReader = cmdSelectMTD.ExecuteReader()
readerMTD.Read()
If IsDBNull(readerMTD.Item(0)) = True Then
If readerVehicle.Item(0) = "Car" Then
ppm = 0.45
Car = "1"
ElseIf readerVehicle.Item(0) = "Motorcycle" Then
ppm = 0.24
Motorcycle = "1"
Else
ppm = 0.2
Pushbike = "1"
End If
Else
If readerVehicle.Item(0) = "Motorcycle" Then
ppm = 0.24
Motorcycle = "1"
ElseIf readerVehicle.Item(0) = "Car" And readerMTD.Item(0) < 10000 Then
ppm = 0.45
Car = "1"
ElseIf readerVehicle.Item(0) = "Car" And readerMTD.Item(0) > 10000 Then
ppm = 0.25
Car = "1"
Else
ppm = 0.2
Pushbike = "1"
End If
End If
readerMTD.Close()
End If
readerVehicle.Close()
myConnectionRemote.Close()
End Using
'VEHICLE TYPE AND PPM ENDS
'insert parameters etc
Dim cmdInsertWE As New SqlCommand(insertString, myConnectionLocal)
cmdInsertWE.Parameters.AddWithValue("#WeekEnding", CType(txtWEDate.Text, DateTime))
cmdInsertWE.Parameters.AddWithValue("#DateProcessed", Now())
cmdInsertWE.Parameters.AddWithValue("#ExpensesFrom", CType(lblMinDate.Text, DateTime))
cmdInsertWE.Parameters.AddWithValue("#ExpensesTo", CType(lblMaxDate.Text, DateTime))
cmdInsertWE.Parameters.AddWithValue("#DateReceived", CType(Session("daterec"), DateTime))
cmdInsertWE.Parameters.AddWithValue("#NovaRef", Session("novaref"))
cmdInsertWE.Parameters.AddWithValue("#IdentifyingNumber", "1")
cmdInsertWE.Parameters.AddWithValue("#SubID", Session("subid"))
cmdInsertWE.Parameters.AddWithValue("#Car", Car)
cmdInsertWE.Parameters.AddWithValue("#Motorcycle", Motorcycle)
cmdInsertWE.Parameters.AddWithValue("#Pushbike", Pushbike)
cmdInsertWE.Parameters.AddWithValue("#MileageCovered", CType(lblMileageNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#MileageAmountClaimed", CType(lblMileageNumber.Text, Decimal) * ppm)
cmdInsertWE.Parameters.AddWithValue("#Accommodation", CType(lblAccommodationNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#Meals", CType(lblMealsNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#DailyAllowance", CType(lblDailyAllowanceNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#ToolsClothing", CType(lblToolsNumber.Text, Decimal) + CType(lblLaundryNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#ToolsDetails", txtToolsDetails.Text)
cmdInsertWE.Parameters.AddWithValue("#Travel", CType(lblTravelNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TelephoneCalls", CType(lblTelephoneCallsNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#ProfessionalFees", CType(lblProfessionalFeesNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#FuelVAT", CType(txtRec_Mileage.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#MAVAT", CType(txtRec_Meals.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TAVAT", CType(txtRec_Travel.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#AVAT", CType(txtRec_Accommodation.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#DAVAT", CType(txtRec_Daily.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TCVAT", CType(txtRec_ToolsLaundry.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TelVAT", CType(txtRec_Telephone.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#PfVAT", CType(txtRec_ProFees.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#processedby", Page.User.Identity.Name)
cmdInsertWE.ExecuteNonQuery()
cmdInsertWE.Dispose()
myConnectionLocal.Close()
'also clear totals labels
lblMileageNumber.Text = 0
lblAccommodationNumber.Text = 0
lblMealsNumber.Text = 0
lblLaundryNumber.Text = 0
lblDailyAllowanceNumber.Text = 0
lblTravelNumber.Text = 0
lblToolsNumber.Text = 0
txtToolsDetails.Text = String.Empty
lblTelephoneCallsNumber.Text = 0
lblProfessionalFeesNumber.Text = 0
End Using 'myConnectionLocal ENDS
'OPEN REMOTE CONNECTION AND UPDATE STATUS OF LIVE TABLES
Using myConnectionRemote As New SqlConnection(dbconnRemote)
myConnectionRemote.Open()
'Mileage()
updateCheckBoxes(MileageGridView, "MileageHeaderCheckBox", "MileageCheckBox", updateMileage, myConnectionRemote, lblMileageNumber)
'Accommodation()
updateCheckBoxes(AccommodationGridView, "AccommodationHeaderCheckBox", "AccommodationCheckBox", updateAccommodation, myConnectionRemote, lblAccommodationNumber)
'Meals()
updateCheckBoxes(MealsGridView, "MealsHeaderCheckBox", "MealsCheckBox", updateMeals, myConnectionRemote, lblMealsNumber)
'Laundry()
updateCheckBoxes(LaundryGridView, "LaundryHeaderCheckBox", "LaundryCheckBox", updateLaundry, myConnectionRemote, lblLaundryNumber)
'Daily(Allowance)
updateCheckBoxes(DailyAllowanceGridView, "DailyAllowanceHeaderCheckBox", "DailyAllowanceCheckBox", updateDailyAllowance, myConnectionRemote, lblDailyAllowanceNumber)
'Travel()
updateCheckBoxes(TravelGridView, "TravelHeaderCheckBox", "TravelCheckBox", updateTravel, myConnectionRemote, lblTravelNumber)
'Tools()
updateCheckBoxes(ToolsGridView, "ToolsHeaderCheckBox", "ToolsCheckBox", updateTools, myConnectionRemote, lblToolsNumber)
'Telephone(Calls)
updateCheckBoxes(TelephoneCallsGridView, "TelephoneCallsHeaderCheckBox", "TelephoneCallsCheckBox", updateTelephoneCalls, myConnectionRemote, lblTelephoneCallsNumber)
'Professional(Fees)
updateCheckBoxes(ProfessionalFeesGridView, "ProfessionalFeesHeaderCheckBox", "ProfessionalFeesCheckBox", updateProfessionalFees, myConnectionRemote, lblProfessionalFeesNumber)
myConnectionRemote.Close()
End Using 'myConnectionRemote ENDS
txtWEDate.Text = String.Empty
End Sub

Related

Select binary image from database and display in Image control

I I am selecting a binary Image from the database with a SELECT query and I would like to display it in a webform but specifically a image control.
This is my code for selecting the image along with other attributes:
Protected Sub btnSearchEmployee_Click(sender As Object, e As EventArgs)
Dim bytes As Byte()
Using br As BinaryReader = New BinaryReader(FileUpload1.PostedFile.InputStream)
bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength)
End Using
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings(##).ToString())
conn.Open()
Dim cmd As New SqlCommand("SELECT EmployeeCodes.ID , Departments.ShortDescription , Departments.Code AS [Department Code] , EmployeeCodes.FirstName , EmployeeCodes.LastName , EmployeeCodes.EmployeeID , EmployeeCodes.Code , EmployeePhoto.Photo FROM EmployeeCodes,EmployeevsPositionLink , PositionCodes , Departments , EmployeePhoto WHERE EmployeePhoto.ID = EmployeeCodes.ID AND EmployeevsPositionLink.EmployeeID = EmployeeCodes.ID AND EmployeevsPositionLink.PositionID = PositionCodes.ID AND PositionCodes.DepartmentCode = Departments.Code AND EmployeeCodes.TerminationDate Is Null AND EmployeevsPositionLink.PositionNumber = '1' AND EmployeeCodes.Company IN (1,3) AND (EmployeeCodes.Code = #code)", conn)
cmd.Parameters.AddWithValue("#code", txtSearchEmployee.Text)
Dim adapter As New SqlDataAdapter(cmd)
Dim tbl As New DataTable()
adapter.Fill(tbl)
If tbl.Rows.Count() > 0 Then
lblID.Text = tbl.Rows(0)(0).ToString()
txtName.Text = tbl.Rows(0)(3).ToString()
txtSurname.Text = tbl.Rows(0)(4).ToString()
txtIDNo.Text = tbl.Rows(0)(5).ToString()
txtCostCentre.Text = tbl.Rows(0)(2).ToString()
txtDepartment.Text = tbl.Rows(0)(1).ToString()
txtClockNo.Text = tbl.Rows(0)(6).ToString()
Else
lblSearchEmployee.Visible = True
lblSearchEmployee.Text = "No employee found with the number" + " " + txtSearchEmployee.Text
End If
conn.Close()
End Using
End Sub

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

Invalid Cast Exception with Update Panel

On Button Click
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
MsgBox("INSIDE")
If SocialAuthUser.IsLoggedIn Then
Dim accountId As Integer = BLL.getAccIDFromSocialAuthSession
Dim AlbumID As Integer = BLL.createAndReturnNewAlbumId(txtStoryTitle.Text.Trim, "")
Dim URL As String = BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim)
Dim dt As New DataTable
dt.Columns.Add("PictureID")
dt.Columns.Add("AccountID")
dt.Columns.Add("AlbumID")
dt.Columns.Add("URL")
dt.Columns.Add("Thumbnail")
dt.Columns.Add("Description")
dt.Columns.Add("AlbumCover")
dt.Columns.Add("Tags")
dt.Columns.Add("Votes")
dt.Columns.Add("Abused")
dt.Columns.Add("isActive")
Dim Row As DataRow
Dim uniqueFileName As String = ""
If Session("ID") Is Nothing Then
lblMessage.Text = "You don't seem to have uploaded any pictures."
Exit Sub
Else
**Dim FileCount As Integer = Request.Form(Request.Form.Count - 2)**
Dim FileName, TargetName As String
Try
Dim Path As String = Server.MapPath(BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim))
If Not IO.Directory.Exists(Path) Then
IO.Directory.CreateDirectory(Path)
End If
Dim StartIndex As Integer
Dim PicCount As Integer
For i As Integer = 0 To Request.Form.Count - 1
If Request.Form(i).ToLower.Contains("jpg") Or Request.Form(i).ToLower.Contains("gif") Or Request.Form(i).ToLower.Contains("png") Then
StartIndex = i + 1
Exit For
End If
Next
For i As Integer = StartIndex To Request.Form.Count - 4 Step 3
FileName = Request.Form(i)
'## If part here is not kaam ka..but still using it for worst case scenario
If IO.File.Exists(Path & FileName) Then
TargetName = Path & FileName
'MsgBox(TargetName & "--- 1")
Dim j As Integer = 1
While IO.File.Exists(TargetName)
TargetName = Path & IO.Path.GetFileNameWithoutExtension(FileName) & "(" & j & ")" & IO.Path.GetExtension(FileName)
j += 1
End While
Else
uniqueFileName = Guid.NewGuid.ToString & "__" & FileName
TargetName = Path & uniqueFileName
End If
IO.File.Move(Server.MapPath("~/TempUploads/" & Session("ID") & "/" & FileName), TargetName)
PicCount += 1
Row = dt.NewRow()
Row(1) = accountId
Row(2) = AlbumID
Row(3) = URL & uniqueFileName
Row(4) = ""
Row(5) = "No Desc"
Row(6) = "False"
Row(7) = ""
Row(8) = "0"
Row(9) = "0"
Row(10) = "True"
dt.Rows.Add(Row)
Next
If BLL.insertImagesIntoAlbum(dt) Then
lblMessage.Text = PicCount & IIf(PicCount = 1, " Picture", " Pictures") & " Saved!"
lblMessage.ForeColor = Drawing.Color.Black
Dim db As SqlDatabase = Connection.connection
Using cmd As DbCommand = db.GetSqlStringCommand("SELECT PictureID,URL FROM AlbumPictures WHERE AlbumID=#AlbumID AND AccountID=#AccountID")
db.AddInParameter(cmd, "AlbumID", Data.DbType.Int32, AlbumID)
db.AddInParameter(cmd, "AccountID", Data.DbType.Int32, accountId)
Using ds As DataSet = db.ExecuteDataSet(cmd)
If ds.Tables(0).Rows.Count > 0 Then
ListView1.DataSource = ds.Tables(0)
ListView1.DataBind()
Else
lblMessage.Text = "No Such Album Exists."
End If
End Using
End Using
'WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.ReturnUrl("~/Memories/SortImages.aspx?id=" & AlbumID))
Else
'TODO:we'll show some error msg
End If
Catch ex As Exception
MsgBox(ex.Message)
lblMessage.Text = "Oo Poop!!"
End Try
End If
Else
WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.LoginWithReturnUrl("~/Memories/CreateAlbum.aspx"))
Exit Sub
End If
End Sub
The above code works fine.I have added an Update Panel in the page to avoid post back, But when i add the button click as a trigger
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" />
</Triggers>
in the update panel to avoid post back, i get the following error.This happens when i add the button click as a Trigger to the update panel.
The Request.Form returns a NameValueCollection which is accessible by the name of the key or the int indexer. It always returns a String and not an Integer.
Dim FileCount As String = Request.Form(Request.Form.Count - 2)
This is all intuition from the exception message, but on the line
FileCount As Integer = Request.Form(Request.Form.Count - 2)
It looks like Request.Form(Request.Form.Count - 2) is a string, and you're trying trying to assign a it to an integer type.
I don't know what you're trying to do, but the string looks like it contains "true" do you want the following?
FileCount As Integer += Boolean.Parse(Request.Form(Request.Form.Count - 2)) ? 1 : 0;

Loop not incrementing ASP.NET VB

'Add items to db'
Function recordOrder()
Dim objDT As System.Data.DataTable
Dim objDR As System.Data.DataRow
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
Dim sql As String
myCommand2.Connection = con2
con2.Open()
'variables'
Dim order_date As String
Dim coupon_ID As String
Dim customer_id As String
Dim quantity As String
'variables'
Try
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
order_date = System.DateTime.Now.Date
coupon_ID = objDR("ID")
quantity = objDR("quantity")
myCommand2.Parameters.Add("#order_date", SqlDbType.VarChar).Value = order_date
myCommand2.Parameters.Add("#coupon_ID", SqlDbType.VarChar).Value = coupon_ID
myCommand2.Parameters.Add("#customer_id", SqlDbType.VarChar).Value = custID
myCommand2.Parameters.Add("#quantity", SqlDbType.VarChar).Value = quantity
myCommand2.CommandText = "INSERT INTO orders(order_date, coupon_id, customer_id, quantity) VALUES ( #order_date ,#coupon_ID,#customer_id,#quantity)"
myCommand2.ExecuteNonQuery()
Next
Catch ex As Exception
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
The loop is not incrementing (intCounter). Please HELP...
Would you not be better to use:
For Each objDR In objDT.Rows
order_date = System.DateTime.Now.Date
coupon_ID = objDR("ID")
quantity = objDR("quantity")
myCommand2.Parameters.Add("#order_date", SqlDbType.VarChar).Value = order_date
myCommand2.Parameters.Add("#coupon_ID", SqlDbType.VarChar).Value = coupon_ID
myCommand2.Parameters.Add("#customer_id", SqlDbType.VarChar).Value = custID
myCommand2.Parameters.Add("#quantity", SqlDbType.VarChar).Value = quantity
myCommand2.CommandText = "INSERT INTO orders(order_date, coupon_id, customer_id, quantity) VALUES ( #order_date ,#coupon_ID,#customer_id,#quantity)"
myCommand2.ExecuteNonQuery()
Next
'custID' is not defined anywhere ..
anyway you should insert a break point and step in with the debugger. Then watch the data to catch which statement is causing the exception. Then modify the code accordingly to handle it.
Where you have:
For intCounter = 0 To objDT.Rows.Count - 1
Replace with:
For intCounter = 0 To objDT.Rows.Count - 1 Step 1
that will increment intCounter by 1 each loop.

get data from database in aspx

i am using VS 2010 to develop a site that gets some data from a database.
but i just keep getting this error.
'No value given for one or more required parameters.'
here is my code
Public Function getSessionDetails(ByVal roomId As String) As ArrayList
Dim sql As String
sql = "SELECT * FROM Table1 WHERE RoomId = ?"
Dim dbComm As New OleDbCommand(sql, dbConn)
'dbComm.Connection.Open()
dbComm.CommandText = sql
dbComm.Parameters.Add("RoomId", System.Data.OleDb.OleDbType.BSTR).Value = roomId
dbConn.Open()
'dbComm.ExecuteNonQuery()
Dim dbRead As OleDbDataReader = dbComm.ExecuteReader() 'System.Data.CommandBehavior.CloseConnection)
Dim arr As New ArrayList
Try
While dbRead.Read()
arr.Add(New SessionDetails(dbRead.GetValue(2).ToString, dbRead.GetValue(3).ToString, dbRead.GetValue(4).ToString, dbRead.GetValue(6).ToString, _
dbRead.GetValue(5).ToString, dbRead.GetValue(7).ToString, dbRead.GetValue(8).ToString))
End While
Catch ex As Exception
End Try
Try
'sort arr by date using bubble
For i As Integer = 1 To arr.Count - 1
Dim sesTop As SessionDetails = arr(i)
Dim sesBot As SessionDetails = arr(i - 1)
Dim sesTmp As SessionDetails
If sesBot.sessionDate < sesTop.sessionDate Then
'swap them
sesTmp = arr(i)
arr(i) = arr(i - 1)
arr(i - 1) = sesTmp
i = 0
ElseIf sesBot.sessionDate = sesTop.sessionDate And sesBot.StartTime < sesTop.StartTime Then
'swap them
sesTmp = arr(i)
arr(i) = arr(i - 1)
arr(i - 1) = sesTmp
i = 0
End If
Next
Catch ex As Exception
End Try
'Dim se As SessionDetails
'For Each se In arr
' If se.sessionDate < Now Then
' arr.Remove(se)
' End If
'Next
dbRead.Close()
dbConn.Close()
Return arr
End Function
Thanks for any help
Change these two lines
sql = "SELECT * FROM Table1 WHERE RoomId = #RoomId"
dbComm.Parameters.Add("#RoomId", System.Data.OleDb.OleDbType.BSTR).Value = roomId
sql = "SELECT * FROM Table1 WHERE RoomId = ?--this is wrong query.
right query is 'sql = "SELECT * FROM Table1 WHERE RoomId = #RoomId'
dbComm.Parameters.Add("#RoomId", System.Data.OleDb.OleDbType.BSTR).Value = RoomId

Resources