Loop not incrementing ASP.NET VB - asp.net

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

Related

Getting id of last inserted row

I have been trying to get the last inserted id into my code but i get 11 or 12 as the returned id, if the parameter type is set to either int 32 or int64 respectively.
This is the procedure i am using
CREATE procedure [dbo].[Sophia_FND_SalesOrder_CREATE](
#contact int,
#deliveryAddress varchar(50),
#Charge float,
#GrossTotal float,
#PaymentMode varchar(50),
#organisationId int,
#userid varchar(50),
#amtpaid float,
#SalesOrderId int OUTPUT
)
as
begin
insert into Sophia_FND_SalesOrder(ContactId, deliveryAddress, Charge, GrossTotal, PaymentMode, organisationId,userid, AmountPaid)
values(#contact,#deliveryAddress, #Charge, #GrossTotal, #PaymentMode, #organisationId, #userid, #amtpaid)
SET #SalesOrderId = SCOPE_IDENTITY()
RETURN #SalesOrderId
end
This is the function i am using in my class
Public Shared Function Create_salesOrder(ByVal contact As Integer, ByVal deliveryAddress As String, ByVal Charge As Double, ByVal GrossTotal As Double, ByVal PaymentMode As String, ByVal organisationId As Integer, ByVal userid As String, ByVal amtpaid As Double) As Integer
Dim comm As DbCommand = CreateCommand17()
comm.CommandText = "Sophia_FND_SalesOrder_CREATE"
AddParameter(comm, "#contact", contact, DbType.Int64)
AddParameter(comm, "#deliveryAddress", deliveryAddress, DbType.String)
AddParameter(comm, "#Charge", Charge, DbType.Double)
AddParameter(comm, "#GrossTotal", GrossTotal, DbType.Double)
AddParameter(comm, "#PaymentMode", PaymentMode, DbType.String)
AddParameter(comm, "#organisationId", organisationId, DbType.Int64)
AddParameter(comm, "#userid", userid, DbType.String)
AddParameter(comm, "#amtpaid", amtpaid, DbType.Double)
AddParameter(comm, "#SalesOrderId", DbType.Int64, ParameterDirection.Output)
Dim id As Integer
Dim insertResult As Int32 = -1
Try
insertResult = ExecuteNonQuery6(comm)
id = Convert.ToInt64(comm.Parameters("#SalesOrderId").Value)
Catch ex As Exception
Throw ex
End Try
'Return insertResult <> -1
Return id
End Function
This is how i call it in my code behind
Dim sale_id As Integer
If IsNothing(Session("soid")) Then
sale_id = Create_salesOrder(CInt(drpcontact.SelectedValue), txtdelivery.Text, lblCharge_unformated.Text, total, drpPayMode.SelectedItem.Text, SessionWrapper.OrganisationId, SessionWrapper.LoggedInUserID, CDbl(txtpayment.Text))
If Not IsNothing(sale_id) Then
Session("soid") = sale_id
Me.MessageBoard1.MessagePanel.CssClass = "errorMessage"
Me.MessageBoard1.MessagePanel.Visible = True
Me.MessageBoard1.MessageLabel.ForeColor = Drawing.Color.Green
Me.MessageBoard1.MessageLabel.Text = "done"
FillGridview()
Else
Me.MessageBoard1.MessagePanel.CssClass = "errorMessage"
Me.MessageBoard1.MessagePanel.Visible = True
Me.MessageBoard1.MessageLabel.ForeColor = Drawing.Color.Red
Me.MessageBoard1.MessageLabel.Text = "Error Occured on creating sales"
End If
end if
I found a way that work but the syntax is entirely different and i would like to stick to my syntax. The problem should be in my class function but i cant seem to know where i did the mistake.
Whenever i run this, i either get 11 or 12 as the return id which is totally wrong
Thanks
Had to change put this in my code behind and this seems to work for me. Thanks
Dim sale_id As Integer
' Dim saleslastid As Integer
Dim salecreate_line As Boolean
If IsNothing(Session("soid")) Then
' slastid = SalesOrder_id()
' saleslastid = StringHelper_2_0.ClearDBNullError(slastid.Rows(0)("id"))
'sale_id = Create_salesOrder(CInt(drpcontact.SelectedValue), txtdelivery.Text, lblCharge_unformated.Text, total, drpPayMode.SelectedItem.Text, SessionWrapper.OrganisationId, SessionWrapper.LoggedInUserID, CDbl(txtpayment.Text))
Dim strConnString As String = ConfigurationManager.ConnectionStrings("SophiaERP_Foundation_4").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Sophia_FND_SalesOrder_CREATE"
cmd.Parameters.Add("#contact", SqlDbType.Int).Value = CInt(drpcontact.SelectedValue)
cmd.Parameters.Add("#deliveryAddress", SqlDbType.VarChar).Value = txtdelivery.Text
cmd.Parameters.Add("#Charge", SqlDbType.Float).Value = lblCharge_unformated.Text
cmd.Parameters.Add("#GrossTotal", SqlDbType.Float).Value = total
cmd.Parameters.Add("#PaymentMode", SqlDbType.VarChar).Value = drpPayMode.SelectedItem.Text
cmd.Parameters.Add("#organisationId", SqlDbType.Int).Value = SessionWrapper.OrganisationId
cmd.Parameters.Add("#userid", SqlDbType.VarChar).Value = SessionWrapper.LoggedInUserID
cmd.Parameters.Add("#amtpaid", SqlDbType.Float).Value = 0
cmd.Parameters.Add("#duration", SqlDbType.Int).Value = CInt(lblduration.Text)
cmd.Parameters.Add("#SalesOrderId", SqlDbType.Int).Direction = ParameterDirection.Output
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
sale_id = cmd.Parameters("#SalesOrderId").Value
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
end if

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 :)

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

SQL Server : very rare Transaction Commit Issue

I am developing a web application with ASP.NET 4.0 with VB.NET as codebehind.
I am using SQL Server 2008 R2 as backend.
I am experiencing very rare problem on a page in my project.
I am entering around two hundred data in textboxes in Telerik Radgrid.
All these information is going to be saved in the database table. When Its saved for the first time, it is working fine and saved in the same order as it is displayed in the grid.
But when I try to update it sometime later, the last row of the grid, it is saved sometimes(not every time) second last in the table. I don't know why and this is my problem I want answer for.
I want the data to stored exactly in the same order as displayed in the grid.
But on update, I find problem with this last row of grid, which is saved second last in table when I commit transaction, it should be saved last.
I am providing VB.NET code below.
Protected Sub SaveBothGridData()
Dim sb1 As New StringBuilder
Dim tran1 As SqlTransaction
Dim tran2 As SqlTransaction
Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("DPMTConnectionString").ConnectionString)
Try
'get the existing datatable
Dim rowIndex As Integer = 0
If ViewState("DT_SR1_section1") IsNot Nothing Then
Dim dtCurrentTable1 As DataTable = DirectCast(ViewState("DT_SR1_section1"), DataTable)
If dtCurrentTable1.Rows.Count > 0 Then
For i As Integer = 0 To dtCurrentTable1.Rows.Count - 1
Dim box1 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox1"), TextBox)
Dim box2 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox2"), TextBox)
Dim box3 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox3"), TextBox)
Dim box4 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox4"), TextBox)
Dim box5 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox5"), TextBox)
Dim box6 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox6"), TextBox)
Dim box7 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox7"), TextBox)
Dim box8 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox8"), TextBox)
Dim box9 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox9"), TextBox)
Dim box10 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox10"), TextBox)
Dim box11 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox11"), TextBox)
Dim box12 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox12"), TextBox)
Dim box13 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox13"), TextBox)
Dim box14 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox14"), TextBox)
dtCurrentTable1.Rows(i)("CAT") = box1.Text
dtCurrentTable1.Rows(i)("PTTL") = box2.Text
dtCurrentTable1.Rows(i)("C1") = box3.Text
dtCurrentTable1.Rows(i)("C2") = box4.Text
dtCurrentTable1.Rows(i)("C3") = box5.Text
dtCurrentTable1.Rows(i)("C4") = box6.Text
dtCurrentTable1.Rows(i)("C5") = box7.Text
dtCurrentTable1.Rows(i)("C6") = box8.Text
dtCurrentTable1.Rows(i)("C7") = box9.Text
dtCurrentTable1.Rows(i)("C8") = box10.Text
dtCurrentTable1.Rows(i)("C9") = box11.Text
dtCurrentTable1.Rows(i)("C10") = box12.Text
dtCurrentTable1.Rows(i)("CTTL") = box13.Text
dtCurrentTable1.Rows(i)("DIFF") = box14.Text
rowIndex += 1
sb1.Append(box1.Text & " " & box2.Text & " " & box3.Text & " " & box4.Text & " " & box5.Text & " " & box6.Text & " " & box7.Text & " " & box8.Text & " " & box9.Text & " " & box10.Text & " " & box11.Text & " " & box12.Text & " " & box13.Text & " " & box14.Text & " " & Now.ToString & vbCrLf)
Next
End If
'save datatable to database
Dim shadingno As Integer = 0
shadingno = Me.hdnShadingNo_section1.Value
cn.Open()
tran1 = cn.BeginTransaction
Dim mode As String = String.Empty
If Not Request.QueryString("shadingno") Is Nothing Then
Dim delcmd As New SqlCommand
delcmd.Connection = cn
delcmd.Transaction = tran1
delcmd.CommandType = CommandType.StoredProcedure
delcmd.CommandText = "sp_delete_shading_return_1_entry"
delcmd.Parameters.Add("#shadingno", SqlDbType.Int).Value = Request.QueryString("shadingno")
delcmd.Parameters.Add("#section", SqlDbType.NVarChar).Value = "section1"
delcmd.ExecuteNonQuery()
End If
'If Not Request.QueryString("shadingno") Is Nothing Then
' Dim obj As New db
' Dim str As String = "delete from shading_return_entry_general where shadingno=" & Request.QueryString("shadingno")
' str = str & ";delete from shading_return_entry_details where shadingno=" & Request.QueryString("shadingno")
' obj.insertAll(str)
' obj = Nothing
'End If
'Dim cmd1 As New SqlCommand
'cmd1.Transaction = tran
'cmd1.Connection = cn
'cmd1.CommandType = CommandType.StoredProcedure
'cmd1.CommandText = "sp_add_update_delete_shading_return_entry_general"
'cmd1.Parameters.Add("#mode", SqlDbType.NVarChar).Value = "ADD"
'cmd1.Parameters.Add("#srno", SqlDbType.Int).Value = 0
'cmd1.Parameters.Add("#shadingno", SqlDbType.Int).Value = shadingno
'cmd1.Parameters.Add("#entrytimestamp", SqlDbType.DateTime).Value = Now
'cmd1.Parameters.Add("#approvalstatus", SqlDbType.NVarChar).Value = "NOT APPROVED"
'cmd1.Parameters.Add("#approvaltimestamp", SqlDbType.DateTime).Value = System.Data.SqlTypes.SqlDateTime.Null
'cmd1.ExecuteNonQuery()
Dim cmd2 As New SqlCommand
cmd2.Transaction = tran1
cmd2.Connection = cn
cmd2.CommandType = CommandType.StoredProcedure
cmd2.CommandText = "sp_add_update_delete_shading_return_1_heading_details"
cmd2.Parameters.Add("#mode", SqlDbType.NVarChar).Value = "ADD"
cmd2.Parameters.Add("#shadingno", SqlDbType.Int).Value = shadingno
cmd2.Parameters.Add("#section", SqlDbType.NVarChar).Value = "section1"
cmd2.Parameters.Add("#col1heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol1Heading_section1.Value)
cmd2.Parameters.Add("#col2heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol2Heading_section1.Value)
cmd2.Parameters.Add("#col3heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol3Heading_section1.Value)
cmd2.Parameters.Add("#col4heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol4Heading_section1.Value)
cmd2.Parameters.Add("#col5heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol5Heading_section1.Value)
cmd2.Parameters.Add("#col6heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol6Heading_section1.Value)
cmd2.Parameters.Add("#col7heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol7Heading_section1.Value)
cmd2.Parameters.Add("#col8heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol8Heading_section1.Value)
cmd2.Parameters.Add("#col9heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol9Heading_section1.Value)
cmd2.Parameters.Add("#col10heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol10Heading_section1.Value)
cmd2.ExecuteNonQuery()
Dim sw As StreamWriter = IO.File.CreateText(Server.MapPath("../ADMIN/") & Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & ".txt")
sw.Write(sb1.ToString)
sw.Flush()
sw.Close()
For i = 0 To dtCurrentTable1.Rows.Count - 1
Dim cmd As New SqlCommand
cmd.Transaction = tran1
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_add_update_delete_shading_return_1_entry_details"
cmd.Parameters.Add("#mode", SqlDbType.NVarChar).Value = "ADD"
cmd.Parameters.Add("#shadingno", SqlDbType.Int).Value = shadingno
cmd.Parameters.Add("#section", SqlDbType.NVarChar).Value = "section1"
cmd.Parameters.Add("#cat", SqlDbType.NVarChar).Value = dtCurrentTable1.Rows(i).Item(0)
cmd.Parameters.Add("#pttl", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(1)
cmd.Parameters.Add("#col1", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(2)
cmd.Parameters.Add("#col2", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(3)
cmd.Parameters.Add("#col3", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(4)
cmd.Parameters.Add("#col4", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(5)
cmd.Parameters.Add("#col5", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(6)
cmd.Parameters.Add("#col6", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(7)
cmd.Parameters.Add("#col7", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(8)
cmd.Parameters.Add("#col8", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(9)
cmd.Parameters.Add("#col9", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(10)
cmd.Parameters.Add("#col10", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(11)
cmd.Parameters.Add("#cttl", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(12)
cmd.Parameters.Add("#diff", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(13)
cmd.ExecuteNonQuery()
Next
tran1.Commit()
'Dim eventMsg As String = "Shading Return entry section1 with shading no " & shadingno & " created"
'Dim obj1 As New com.hemalrathod.dpmt.DatabaseHandling
'obj1.SaveToUserEventLog(Request.Cookies.Item("loginname").Value, "Shading return entry 1 create", eventMsg, Now, Request.Cookies.Item("clientipaddress").Value)
'obj1 = Nothing
'Response.Redirect("Shading_View.aspx")
Else
Response.Write("ViewState is null")
End If
Catch ex As Exception
Response.Write(ex.Message)
Finally
cn.Close()
End Try
End Sub
In the above code, I am creating a transaction to save the data, when updating, I first delete the original data and then saving the new one.
Problem is with only first transaction 'tran1'. I haven't found any problem with 'tran2'.
I think problem is with committing transaction. When its committed, somehow, the last row of grid, is saved second last in the table.
Following is the SQL Server procedure I used
Procedure for deleting the existing data before entering new data
ALTER procedure [dbo].[sp_delete_shading_return_1_entry]
(
#shadingno int,
#section nvarchar(50)
)
as
delete from shading_return_1_heading_details
where shadingno = #shadingno and section = #section
delete from shading_return_1_entry_details
where shadingno = #shadingno and section = #section
delete from shading_return_entry_general
where shadingno = #shadingno
Procedure for entering new heading data(this is not creating any problem)
ALTER procedure [dbo].[sp_add_update_delete_shading_return_1_heading_details]
(
#mode nvarchar(50),
#shadingno int,
#section nvarchar(50),
#col1heading nvarchar(50),
#col2heading nvarchar(50),
#col3heading nvarchar(50),
#col4heading nvarchar(50),
#col5heading nvarchar(50),
#col6heading nvarchar(50),
#col7heading nvarchar(50),
#col8heading nvarchar(50),
#col9heading nvarchar(50),
#col10heading nvarchar(50)
)
as
if #mode='ADD'
begin
insert into shading_return_1_heading_details values(#shadingno, #section, #col1heading, #col2heading, #col3heading, #col4heading, #col5heading, #col6heading, #col7heading, #col8heading, #col9heading, #col10heading)
end
Procedure to store data from radgrid to the table(THIS IS ACTUALLY WHERE ERROR MIGHT BE)
ALTER procedure [dbo].[sp_add_update_delete_shading_return_1_entry_details]
(
#mode nvarchar(50),
#shadingno int,
#section nvarchar(50),
#cat nvarchar(50),
#pttl float,
#col1 float,
#col2 float,
#col3 float,
#col4 float,
#col5 float,
#col6 float,
#col7 float,
#col8 float,
#col9 float,
#col10 float,
#cttl float,
#diff float
)
as
if #mode='ADD'
begin
insert into shading_return_1_entry_details
values(#shadingno, #section, #cat, #pttl, #col1, #col2, #col3, #col4, #col5, #col6, #col7, #col8, #col9, #col10, #cttl, #diff)
end
After this, as per my VB.NET code, I am committing 'tran1' transaction, and then problem occurs sometimes not often.
In short, I want all rows in radgrid to be stored exactly in the same order, but after committing transaction, sometimes, the last row of grid, is stored second last in the table.
How can I solve this?
Thank you in advance

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

Resources