Updated Code
VB CODEBEHIND
Protected Sub cmdclick_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdclick.Click
Dim strConnString As String = WebConfigurationManager.ConnectionStrings("orca").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand("usp_validatecard", con)
cmd.CommandType = Data.CommandType.StoredProcedure
Dim GetTrack1 As String = ""
Dim GetTrack2 As String = ""
Dim SplitTrack As String = txtTrack.Text
If SplitTrack.Length.ToString = 19 Then
GetTrack1 = Mid(SplitTrack, 2, 6)
GetTrack2 = Mid(SplitTrack, 10, 9)
cmd.Parameters.Add("#track1", Data.SqlDbType.NVarChar).Value = GetTrack1
cmd.Parameters.Add("#track2", Data.SqlDbType.NVarChar).Value = GetTrack2
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
ElseIf SplitTrack.Length.ToString = 8 Then
GetTrack1 = Mid(SplitTrack, 2, 6)
cmd.Parameters.Add("#track1", Data.SqlDbType.NVarChar).Value = GetTrack1
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
ElseIf SplitTrack.Length.ToString = 11 Then
GetTrack2 = Mid(SplitTrack, 2, 9)
cmd.Parameters.Add("#track2", Data.SqlDbType.NVarChar).Value = GetTrack2
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
Else
lblmessage.Text = "Could Not Find Any Tracks"
End If
MSSQL STORED PROCEDURE
ALTER Procedure [dbo].[usp_validatecard](
#memnum nvarchar(50) = '-',
#memname nvarchar(50) = '-',
#track1 nvarchar(50) = '-',
#track2 nvarchar(50) = '-',
#msgtrack1 nvarchar(50) = 'Track 1 is Blank',
#msgtrack2 nvarchar(50) = 'Track 2 is Blank',
#message nvarchar(100)= '-')
As
--select #cardid = '%128255? ;282556587?'
--select #track1 = '128255'
--select #track2 = '282556587'
-- track1 good, track2 good
If exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 = #track2 or CLUBCARD2 = #track2))
begin
select #memname = lastname + ', ' + firstname, #memnum = MEMBERSHIPID from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 = #track2 or CLUBCARD2 = #track2)
if exists(select * from dbo.clubmembers where membershipid = #memnum and status = 'ACTIVE')
select #msgtrack1 = 'Track 1 is GOOD', #msgtrack2 = 'Track 2 is GOOD', #message = 'Card is GOOD'
else
select #msgtrack1 = 'Track 1 is GOOD but In-active', #msgtrack2 = 'Track 2 is GOOD but In-active', #message = 'Check Member Status in Membership'
end
-- track1 good and track2 bad
Else
If exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2))
begin
select #memname = lastname, #memnum = FAMILYID from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2)
if exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2) and status = 'ACTIVE')
select #msgtrack1 = 'Track 1 is GOOD', #msgtrack2 = 'Track 2 is BAD', #message = 'Please re-encode card'
else
select #msgtrack1 = 'Track 1 is GOOD but In-Active', #msgtrack2 = 'Track 2 is BAD', #message = 'Please re-encode card and Check Member Status in Membership'
end
else
-- track1 bad, track2 good
If exists(select * from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2) and FAMILYID != #track1)
begin
select #memname = lastname + ', ' + firstname, #memnum = MEMBERSHIPID from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2)
If exists(select * from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2) and FAMILYID != #track1 and STATUS = 'ACTIVE')
select #msgtrack1 = 'Track 1 is BAD', #msgtrack2 = 'Track 2 is GOOD', #message = 'Please re-encode card'
else
select #msgtrack1 = 'Track 1 is BAD', #msgtrack2 = 'Track 2 is GOOD but In-active', #message = 'Please re-encode card and Check member status in Membership'
end
select #memname, #memnum, #msgtrack1, #msgtrack2, #message
If you check if sp has two elements or not by doing
If sp.Length = 2 Then
...
End If
and inside the If block, you can do
Dim track1 as String = sp(0)
Dim track2 as String = sp(1)
C# is more to my liking but this is a rough cut of a method that will split your string, test for correct number of elements and then create database connection (assumed sql server but any ole db should work) and call your stored procedure.
Public Sub ProcessSwipe(ByVal value As String)
Dim splitValues() As String
Dim separator As Char = ";"
Dim connectionString As String = String.Empty
Dim storedProcName As String = String.Empty
' Edit these to sane values
connectionString = "Provider=SQLOLEDB;BData Source=localhost;Initial Catalog=msdb;Integrated Security=SSPI;"
storedProcName = "dbo.SaveSwipe"
If String.IsNullOrEmpty(value) Then
MsgBox("No value provided from swipe")
Return
End If
Try
splitValues = value.Split(separator)
If splitValues.Length <> 2 Then
MsgBox(String.Format("Splitting of swipe data did not result in 2 values. Swiped value is {0}", value))
Return
End If
' At this point, we should have an array with 2 elements in it
' Open a connection
Using connection As New OleDb.OleDbConnection(connectionString)
connection.Open()
Using Command As New OleDb.OleDbCommand
Command.CommandText = storedProcName
Command.CommandType = CommandType.StoredProcedure
Command.Connection = connection
' Assumes your proc takes 2 parameters, named swipe1 and swipe2
' Update to sane values
Command.Parameters.AddWithValue("#swipe1", splitValues(0))
Command.Parameters.AddWithValue("#swipe2", splitValues(1))
' Make the actual call to your stored procedure
Command.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox(String.Format("Attempt to split {0} failed. {1}", value, ex))
End Try
End Sub
Sub Main()
Dim shorty As String
Dim works As String
Dim longun As String
Dim nuthin As String
shorty = "%128565?"
works = "%128565?;229584115?"
longun = "%128565?;229584115?%128565?;229584115?"
nuthin = Nothing
ProcessSwipe(shorty)
ProcessSwipe(works)
ProcessSwipe(longun)
ProcessSwipe(nuthin)
End Sub
Related
I am working on a cart/basket page of an e-commerce site. Specifically: "-" link button to decrease quantity of selected product by 1 in the cart, and later the "+" link button to increase quantity of selected product by 1 in the cart.
For the "-" button I am doing:
Check the CategoryID of the product selected.
If the CategoryID = 3 or 4, then:
Check if the quantity of the selected product is more > 1.
Quantity = Quantity - 1.
Reduce the amount of HoursWork (used for booking slot length) for the selected product.
Product Stock + 1.
Reduce the weight (used for delivery price).
Else: label displays "Quantity cannot be changed for Detailing & Valeting services.
I am using a SqlDataReader to get the CategoryID, and then storing it as Integer in variable CategoryID.
I tested by displaying the variable contents in a label, and it collects the correct CategoryID - however the "If CategoryID = "3" or "4" Then... is not working, as all categoryIDs are running the IF section or the statement and not the ELSE section.
Protected Sub lDecrease_Click(ByVal sender As Object, ByVal e As EventArgs)
'get clicked button
Dim lnk As LinkButton = CType(sender, LinkButton)
'Get clicked button row
' Dim row As GridViewRow = CType(lnk.Parent.Parent, GridViewRow)
Dim row As GridViewRow = CType(lnk.NamingContainer, GridViewRow)
'Get row selected
Dim idx As Integer = row.RowIndex
'get CartID
Dim lblCartID As Label = CType(row.Cells(0).FindControl("lblCartID"), Label)
Dim SCCartID As String = lblCartID.Text.ToString
'get ProductID
Dim lblProductID As Label = CType(row.Cells(0).FindControl("lblProductID"), Label)
Dim SCProductID As String = lblProductID.Text.ToString
'get ProductName
Dim lblProduct As Label = CType(row.Cells(0).FindControl("lblProduct"), Label)
Dim SCProduct As String = lblProduct.Text.ToString
'get Size
Dim lblSize As Label = CType(row.Cells(0).FindControl("lblSize"), Label)
Dim SCSize As String = lblSize.Text.ToString
'get Price
Dim lblPrice As Label = CType(row.Cells(0).FindControl("lblPrice"), Label)
Dim SCPrice As String = lblPrice.Text.ToString
'get Quantity
Dim lblQuantity As Label = CType(row.Cells(0).FindControl("lblQuantity"), Label)
Dim SCQuantity As String = lblQuantity.Text.ToString
'get Subtotal
Dim lblSubtotal As Label = CType(row.Cells(0).FindControl("lblSubtotal"), Label)
Dim SCSubtotal As String = lblSubtotal.Text.ToString
'get HoursWork
Dim lblHoursWork As Label = CType(row.Cells(0).FindControl("lblHoursWork"), Label)
Dim SCHoursWork As String = lblHoursWork.Text.ToString
'get Weight
Dim lblWeight As Label = CType(row.Cells(0).FindControl("lblWeight"), Label)
Dim SCWeight As String = lblWeight.Text.ToString
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
' start of category check
Dim cmd4 As SqlCommand = New SqlCommand
cmd4.CommandText = "SELECT products.CategoryID FROM products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE cart.productID=#ProductID"
Dim ProductID2 As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID2.Value = SCProductID
cmd4.Parameters.Add(ProductID2)
cmd4.Connection = conn
conn.Open()
cmd4.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
'Testing CategoryID value = success
lblNoStock.Visible = True
lblNoStock.Text = CategoryID
conn.Close()
'Nest IF statement based on Category ID 1,2, cannot be reduced in Quantity
If CategoryID = "3" Or "4" Then
' Run quantity check – And update if possible
Dim exists As Boolean = False
'cart quantity
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "Select Quantity from Cart where CartID = #CartID"
cmd.Connection = conn
' conn.Close()
conn.Open()
'rename cart id 5
Dim CartID5 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID5.Value = SCCartID
cmd.Parameters.Add(CartID5)
'check if more than 1 in cart
exists = (CType(cmd.ExecuteScalar, Integer) > 1)
If exists Then
'show label to say no more in stock
lblNoStock.Visible = True
' lblNoStock.Text = "Available!"
conn.Close()
' update quantity & subtotal
Dim cmd1 As SqlCommand = New SqlCommand
cmd1.CommandText = "UPDATE Cart SET Quantity = Quantity - 1, Subtotal = #Subtotal - #Price WHERE CartID = #CartID"
'update hourswork
Dim cmd2 As SqlCommand = New SqlCommand
cmd2.CommandText = "UPDATE Cart SET HoursWork = (HoursWork - (Select Products.HoursWork FROM Products WHERE Products.ProductID = Cart.ProductID)) WHERE CartID = #CartID"
'UPDATE PRODUCTS STOCK + 1
'"UPDATE Products Set Stock = Stock + 1 WHERE ProductID = #ProductID"
Dim cmd3 As SqlCommand = New SqlCommand
'UPDATE weight
cmd3.CommandText = "UPDATE Cart SET Weight = (Weight - (Select Products.Weight FROM Products WHERE Products.ProductID = Cart.ProductID)) WHERE CartID = #CartID"
cmd1.Connection = conn
cmd2.Connection = conn
cmd3.Connection = conn
conn.Open()
Dim PProductID As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
PProductID.Value = SCProductID
cmd1.Parameters.Add(PProductID)
Dim Subtotal As SqlParameter = New SqlParameter("#Subtotal", SqlDbType.Decimal, 5)
Subtotal.Value = SCSubtotal
cmd1.Parameters.Add(Subtotal)
Dim Price As SqlParameter = New SqlParameter("#Price", SqlDbType.Decimal, 5)
Price.Value = SCPrice
cmd1.Parameters.Add(Price)
Dim CartID As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID.Value = SCCartID
cmd1.Parameters.Add(CartID)
Dim CartID2 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID2.Value = SCCartID
cmd2.Parameters.Add(CartID2)
Dim CartID3 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID3.Value = SCCartID
cmd3.Parameters.Add(CartID3)
Try
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
cmd.ExecuteReader()
'show label to quantity updated
lblNoStock.Visible = True
' lblNoStock.Text = "Updated!"
Finally
conn.Close()
'Response.Redirect("Cart2.aspx")
End Try
Else
'show label to say no more in stock
lblNoStock.Visible = True
lblNoStock.Text = "Cannot reduce quantity: Remove from Cart!"
End If
' else
' lblNoStock.Visible = True
' lblNoStock.Text = "Cannot reduce quantity of Detailing/ Valeting services: Remove from Cart!"
Else
'Outer ELSE
'show label to say cannot change quantity
lblNoStock.Visible = True
lblNoStock.Text = "Quantity cannot be changed for Detailing and Valeting services!"
End If
End Sub
I am also having the same issue with the "+" link button to increase quantity of selected product by 1 in the cart. Reduced code:
Protected Sub lIncrease_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
Dim exists As Boolean = False
'Check available in Products table STOCK
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "Select Stock from Products where ProductID = #ProductID"
cmd.Connection = conn
conn.Open()
Dim ProductID As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID.Value = SCProductID
cmd.Parameters.Add(ProductID)
'check if more than 0 in stock
exists = (CType(cmd.ExecuteScalar, Integer) > 0)
If exists Then
conn.Close()
Dim cmd4 As SqlCommand = New SqlCommand
cmd4.CommandText = "SELECT products.CategoryID FROM products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE cart.productID=#ProductID"
Dim ProductID2 As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID2.Value = SCProductID
cmd4.Parameters.Add(ProductID2)
cmd4.Connection = conn
conn.Open()
cmd4.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
'Testing CategoryID value = success
' lblNoStock.Visible = True
'lblNoStock.Text = CategoryID
conn.Close()
'NESTED IF STATEMENT
If CategoryID = "3" Or "4" Then
' UPDATE cart QUANTITY & SUBTOTAL based on CartID
cmd1.CommandText = "UPDATE Cart SET Quantity = Quantity + 1, Subtotal = #Subtotal + #Price WHERE CartID = #CartID"
Dim cmd2 As SqlCommand = New SqlCommand
'UPDATE cart HOURSWORK
cmd2.CommandText = "/"
Dim cmd3 As SqlCommand = New SqlCommand
'UPDATE cart HOURSWORK
cmd3.CommandText = "/"
cmd1.Connection = conn
cmd2.Connection = conn
cmd3.Connection = conn
conn.Open()
//Declared Parameters
Try
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
cmd.ExecuteReader()
Finally
conn.Close()
Response.Redirect("Cart2.aspx")
End Try
Else
'Nested ELSE
'show label to say cannot change quantity
lblNoStock.Visible = True
lblNoStock.Text = "Quantity cannot be changed for Detailing and Valeting services!"
End If
Else
'show label to say no more in stock
lblNoStock.Visible = True
lblNoStock.Text = "Sorry out of stock!"
End If
End Sub
Two tables:
CART (CartID, UserID, DateCreated, ProductID, ProductName, Size, Price, Quantity, Subtotal, HoursWork)
PRODUCTS (ProductID, Name, SDescription, Price, Size, Images, Thumbnail, Weight, LDescription, Stock, CategoryID, HoursWork)
All working correctly now.
Changed from:
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
conn.Close()
If CategoryID = "3" Or "4" Then
To:
Dim reader As SqlDataReader = cmd4.ExecuteReader
While reader.Read()
lblTest3.Text = CType(reader.Item("CategoryID"), Integer)
End While
conn.Close()
If lblTest3.Text.Contains("3") Or lblTest3.Text.Contains("4") Then
The read record is solved. I still have another problem the error message still remain there after user key in correct order id.
query = "select FoodName, Qty, IngredientName, Quantity, OrderStatus
from tblorder, tblorderdetail, tblfood, tblcustomizefooddetail, tblcustomizeingredient, tblordercustomize
where tblOrder.OrderId = #OrderId and OrderStatus = #OrderStatus and tblorder.OrderId = tblorderdetail.OrderId and tblorderdetail.FoodId = tblfood.FoodId and tblorderdetail.OrderDetailId = tblordercustomize.OrderDetailId and tblfood.FoodId = tblcustomizefooddetail.FoodId and tblcustomizeingredient.IngredientId = tblcustomizefooddetail.IngredientId and tblordercustomize.IngredientId = tblcustomizeingredient.IngredientId"
com = New MySqlCommand(query, conn)
com.Parameters.AddWithValue("#OrderId", txtOrderId.Text)
com.Parameters.AddWithValue("#OrderStatus", "Pending")
Dim sqladapter As New MySqlDataAdapter(com)
sqladapter.Fill(dt)
If dt.Rows.Count Then
GridView1.DataSource = dt
GridView1.DataBind()
Else
Label1.Text = "Order ID Doesn't Exist"
End If
Lets take your sample and modify it:
query = "select FoodName, Qty, IngredientName, Quantity, OrderStatus
from tblorder, tblorderdetail, tblfood, tblcustomizefooddetail, tblcustomizeingredient, tblordercustomize
where tblOrder.OrderId = #OrderId and OrderStatus = #OrderStatus and tblorder.OrderId = tblorderdetail.OrderId and tblorderdetail.FoodId = tblfood.FoodId and tblorderdetail.OrderDetailId = tblordercustomize.OrderDetailId and tblfood.FoodId = tblcustomizefooddetail.FoodId and tblcustomizeingredient.IngredientId = tblcustomizefooddetail.IngredientId and tblordercustomize.IngredientId = tblcustomizeingredient.IngredientId"
com = New MySqlCommand(query, conn)
com.Parameters.AddWithValue("#OrderId", txtOrderId.Text)
com.Parameters.AddWithValue("#OrderStatus", "Pending")
Dim adapter as new SqlDataAdapter(com)
adapter.Fill(dt)
if adapter.Tables(0).Rows.Count > 0
GridView1.DataSource = adapter.Tables(0)
GridView1.DataBind()
Else
Label1.Text = "Order ID Doesn't Exist"
End If
I am using this code to update database with new values. But it return message The thread was interrupted. What does it mean? What is wrong with my code?
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("DeskriptivaConnectionString").ConnectionString.ToString()
Dim txtName As Object = DirectCast(FormView1.FindControl("txtName"), TextBox)
Dim txtLastName As Object = DirectCast(FormView1.FindControl("txtLastName"), TextBox)
Dim txtInfo As Object = DirectCast(FormView1.FindControl("txtInfo"), TextBox)
Dim txtCity As Object = DirectCast(FormView1.FindControl("txtCity"), TextBox)
Dim txtPrize As TextBox = DirectCast(FormView1.FindControl("txtPrize"), TextBox)
Dim txtPhone As TextBox = DirectCast(FormView1.FindControl("txtPhone"), TextBox)
Dim txtMail As TextBox = DirectCast(FormView1.FindControl("txtMail"), TextBox)
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE Profiles SET #Name = Name, #LastName = LastName, #Info = Info, #City = City, #Prize = Prize, #Phone = Phone, #Mail = Mail WHERE (UserName = #UserName)"
cmd.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar).Value = txtName.Text
cmd.Parameters.Add("#LastName", System.Data.SqlDbType.NVarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Info", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtInfo.Text))
cmd.Parameters.Add("#City", System.Data.SqlDbType.NVarChar).Value = txtCity.Text
cmd.Parameters.Add("#Prize", System.Data.SqlDbType.NVarChar).Value = txtPrize.Text
cmd.Parameters.Add("#Phone", System.Data.SqlDbType.NVarChar).Value = txtPhone.Text
cmd.Parameters.Add("#Mail", System.Data.SqlDbType.NVarChar).Value = txtMail.Text
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(ResolveClientUrl("~/Profil/"))
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Use Response.Redirect(ResolveClientUrl("~/Profil/"), false) with Context.ApplicationInstance.CompleteRequest(); instead of Response.Redirect(ResolveClientUrl("~/Profil/"))
check Correct use of System.Web.HttpResponse.Redirect blog post for more information
and also your sql parameters # symbol is in wrong place. change as below
UPDATE Profiles SET
Name = #Name, LastName
= #LastName, Info =
#Info, City = #City,
Prize = #Prize, Phone
= #Phone, Mail = #Mail
WHERE (UserName =
#UserName)
I am getting this error
No mapping exists from object type System.String[] to a known managed provider native type.
The code is
Dim conn1 As SqlConnection
conn1 = New SqlConnection("Data Source=win2008-2;Initial Catalog=h1tm11;User ID=sa;Password=#1cub3123*;Persist Security Info=True;")
' Dim conn1 As String = ConfigurationManager _ .ConnectionStrings("Connectionstring").ConnectionString()
'conn1.ConnectionString = ConfigurationManager.ConnectionStrings("Data Source=win2008-2;Initial Catalog=h1tm11;User ID=sa;Password=#1cub3123*;Persist Security Info=True;").ConnectionString
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = "SELECT lat,lng FROM tbl_pincode WHERE codes LIKE #Value"
Dim addressstring1 As String = txtpostcode.Value.Trim()
Dim addressstring() As String = Split("addressstring1", ",", 1)
'SqlCommand cmd = new SqlCommand(query,conn1);
cmd.Parameters.AddWithValue("#Value", addressstring)
Dim table As DataTable
table = New DataTable()
Dim adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
adapter.SelectCommand = cmd
adapter.SelectCommand.Connection = conn1
adapter.Fill(table)
' Dim row As DataRow
' For Each number As Integer In New Long()
For Each row As DataRow In table.Rows
Dim lat As String = row("lat").ToString()
Dim lng As String = row("lng").ToString()
Dim connstring As SqlConnection = New SqlConnection()
connstring.ConnectionString = ConfigurationManager.ConnectionStrings("Data Source=win2008-2;Initial Catalog=h1tm11;User ID=sa;Password=#1cub3123*;Persist Security Info=True;").ConnectionString
Dim conn As SqlCommand = New SqlCommand()
conn.CommandText = "SELECT *, 6371.01 * ACOS( SIN( CAST((#lat) AS float)*PI()/180 ) * SIN( CAST((store_lat) AS float)*PI()/180 ) + COS( CAST((#lat) AS float)*PI()/180 ) * COS( CAST((store_lat) AS float)*PI()/180 ) * COS( (CAST((store_long) AS float)*PI()/180) - (CAST((#lng) AS float)*PI()/180) ) ) AS distance from storelocator where 6371.01 * ACOS( SIN(CAST((#lat) AS float)*PI()/180 ) * SIN( CAST((store_lat) AS float)*PI()/180 ) + COS(CAST((#lat) AS float)*PI()/180 ) * COS( CAST((store_lat) AS float)*PI()/180 ) * COS( (CAST((store_long) AS float)*PI()/180) - (CAST((#lng) AS float)*PI()/180) ) ) < '" + withddl.SelectedItem.Value + "' order by distance asc;"
conn.Connection.Open()
'SqlCommand comm = new SqlCommand(SQL1, conn);
conn.Parameters.AddWithValue("#lat", lat)
conn.Parameters.AddWithValue("#lng", lng)
Dim reader As SqlDataReader = conn.ExecuteReader()
While (reader.Read())
Dim area As String = reader("store_name").ToString()
Dim codes As String = reader("store_address1").ToString()
litAddress.Text += area + "<br>"
litAddress.Text += codes + "<br>" + "<br>"
End While
Next
the error occurs at adapter.Fill(table)
I think the problem is in
Dim addressstring1 As String = txtpostcode.Value.Trim()
Dim addressstring() As String = Split("addressstring1", ",", 1)
Can someone plz help me out?
addressstring is a string array.
You can't pass an array as a SQL parameter, since SQL Server does not support arrays.
Below is the code that i used to load the data into treeview from database! But i feel like it's a bit laggy while retrieving...is thr any way to optimize it?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not IsPostBack Then
PopulateRootLevel("0", "ALL")
End If
Catch ex As Exception
MSGMgr.errHandlerSys(ex.Message, lblMsg)
End Try
End Sub
Private Sub PopulateRootLevel(ByVal LvlCD As String, ByVal scheme As String)
Dim objConn As New SqlConnection(DBMgr.asyncADOCnnStr("SQL"))
Dim objCommand As SqlCommand
If scheme = "ALL" Then
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, GroupNo, Descriptions Title, (SELECT DISTINCT COUNT(*) FROM i_Menu_Access WHERE GroupNo = prt.GroupNo and SubItemNo1='0' AND LevelCD='0' AND ItemNo <> '0') SubItemCnt FROM i_Menu_Access prt WHERE ItemNo = '0' AND LevelCD = '" & LvlCD & "' ORDER BY GroupNo", objConn)
Else
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, GroupNo, Descriptions Title, (SELECT DISTINCT COUNT(*) FROM i_Menu_Access WHERE GroupNo = prt.GroupNo and SubItemNo1='0' AND LevelCD='0' AND ItemNo <> '0') SubItemCnt FROM i_Menu_Access prt WHERE ItemNo = '0' AND LevelCD = '" & LvlCD & "' AND Level3 = #Scheme ORDER BY GroupNo", objConn)
objCommand.Parameters.Add("#Scheme", SqlDbType.VarChar).Value = scheme
End If
Dim da As New SqlDataAdapter(objCommand)
Dim dt As New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim child As New TreeNode()
child.Text = dr("Title").ToString().Trim()
child.Value = dr("ID").ToString().Trim()
Dim GrpNo As String = dr("GroupNo").ToString().Trim()
child.ToolTip = "Click to get Child"
child.SelectAction = TreeNodeSelectAction.SelectExpand
child.CollapseAll()
tvMenuTable.Nodes.Add(child)
PopulateSubLevel(GrpNo, LvlCD, child, scheme)
Next
End Sub
Private Sub PopulateSubLevel(ByVal parentid As Integer, ByVal LvlCD As String, ByVal parentNode As TreeNode, ByVal scheme As String)
Dim objConn As New SqlConnection(DBMgr.asyncADOCnnStr("SQL"))
Dim objCommand As SqlCommand
If scheme = "ALL" Then
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, ItemNo, cast(groupno as varchar)+'|'+cast(itemno as varchar)+'|'+cast(subitemno1 as varchar) ID2, Descriptions Title, (SELECT DISTINCT COUNT(*) FROM i_Menu_Access WHERE GroupNo = prt.GroupNo AND ItemNo = prt.ItemNo AND SubItemNo1 <> '0' AND SubItemNo2 = '0' AND LevelCD = '0') SubItemCnt FROM i_Menu_Access prt WHERE LevelCD = #LvlCD AND GroupNo = #parentID AND ItemNo <> '0' AND SubItemNo1 = '0' ORDER BY ItemNo", objConn)
objCommand.Parameters.Add("#parentID", SqlDbType.Int).Value = parentid
objCommand.Parameters.Add("#LvlCD", SqlDbType.VarChar).Value = LvlCD
Else
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, ItemNo, cast(groupno as varchar)+'|'+cast(itemno as varchar)+'|'+cast(subitemno1 as varchar) ID2, Descriptions Title, (SELECT DISTINCT COUNT(*) FROM i_Menu_Access WHERE GroupNo = prt.GroupNo AND ItemNo = prt.ItemNo AND SubItemNo1 <> '0' AND SubItemNo2 = '0' AND LevelCD = '0') SubItemCnt FROM i_Menu_Access prt WHERE LevelCD = #LvlCD AND GroupNo = #parentID AND ItemNo <> '0' AND SubItemNo1 = '0' AND Level3 = #Scheme ORDER BY ItemNo", objConn)
objCommand.Parameters.Add("#parentID", SqlDbType.Int).Value = parentid
objCommand.Parameters.Add("#LvlCD", SqlDbType.VarChar).Value = LvlCD
objCommand.Parameters.Add("#Scheme", SqlDbType.VarChar).Value = scheme
End If
Dim da As New SqlDataAdapter(objCommand)
Dim dt As New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim child As New TreeNode()
child.Text = dr("Title").ToString().Trim()
child.Value = dr("ID").ToString().Trim()
Dim ID() As String
ID = dr("ID2").ToString().Trim().Split("|")
child.ToolTip = "Click to get Child"
child.SelectAction = TreeNodeSelectAction.SelectExpand
child.CollapseAll()
parentNode.ChildNodes.Add(child)
PopulateThirdLevel(ID(0), ID(1), LvlCD, child, scheme)
Next
End Sub
Private Sub PopulateThirdLevel(ByVal lvlOneID As Integer, ByVal lvlTwoID As Integer, ByVal LvlCD As String, ByVal parentNode As TreeNode, ByVal scheme As String)
Dim objConn As New SqlConnection(DBMgr.asyncADOCnnStr("SQL"))
Dim objCommand As SqlCommand
If scheme = "ALL" Then
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, ItemNo, SubItemNo1, cast(groupno as varchar)+'|'+cast(itemno as varchar)+'|'+cast(subitemno1 as varchar) ID2, Descriptions Title FROM i_Menu_Access WHERE LevelCD = #LvlCD AND GroupNo = #lvlOneID AND ItemNo = #lvlTwoID AND ItemNo <> '0' AND SubItemNo1 <> '0' AND SubItemNo2 = '0' ORDER BY SubItemNo1", objConn)
objCommand.Parameters.Add("#lvlOneID", SqlDbType.Int).Value = lvlOneID
objCommand.Parameters.Add("#lvlTwoID", SqlDbType.Int).Value = lvlTwoID
objCommand.Parameters.Add("#LvlCD", SqlDbType.VarChar).Value = LvlCD
Else
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, ItemNo, SubItemNo1, cast(groupno as varchar)+'|'+cast(itemno as varchar)+'|'+cast(subitemno1 as varchar) ID2, Descriptions Title FROM i_Menu_Access WHERE LevelCD = #LvlCD AND GroupNo = #lvlOneID AND ItemNo = #lvlTwoID AND ItemNo <> '0' AND SubItemNo1 <> '0' AND SubItemNo2 = '0' AND Level3 = #Scheme ORDER BY SubItemNo1", objConn)
objCommand.Parameters.Add("#lvlOneID", SqlDbType.Int).Value = lvlOneID
objCommand.Parameters.Add("#lvlTwoID", SqlDbType.Int).Value = lvlTwoID
objCommand.Parameters.Add("#LvlCD", SqlDbType.VarChar).Value = LvlCD
objCommand.Parameters.Add("#Scheme", SqlDbType.VarChar).Value = scheme
End If
Dim da As New SqlDataAdapter(objCommand)
Dim dt As New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim child As New TreeNode()
child.Text = dr("Title").ToString().Trim()
child.Value = dr("ID").ToString().Trim()
Dim ID() As String
ID = dr("ID2").ToString().Trim().Split("|")
child.SelectAction = TreeNodeSelectAction.SelectExpand
child.CollapseAll()
parentNode.ChildNodes.Add(child)
Populate4thLevel(ID(0), ID(1), ID(2), LvlCD, child, scheme)
Next
End Sub
Private Sub Populate4thLevel(ByVal lvlOneID As Integer, ByVal lvlTwoID As Integer, ByVal lvl3rdID As Integer, ByVal LvlCD As String, ByVal parentNode As TreeNode, ByVal scheme As String)
Dim objConn As New SqlConnection(DBMgr.asyncADOCnnStr("SQL"))
Dim objCommand As SqlCommand
If scheme = "ALL" Then
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, ItemNo, SubItemNo2, Descriptions Title FROM i_Menu_Access WHERE LevelCD = #LvlCD AND GroupNo = #lvlOneID AND ItemNo = #lvlTwoID AND SubItemNo1 = #lvl3rdID AND SubItemNo2 <> '0' ORDER BY SubItemNo2", objConn)
objCommand.Parameters.Add("#lvlOneID", SqlDbType.Int).Value = lvlOneID
objCommand.Parameters.Add("#lvlTwoID", SqlDbType.Int).Value = lvlTwoID
objCommand.Parameters.Add("#lvl3rdID", SqlDbType.Int).Value = lvl3rdID
objCommand.Parameters.Add("#LvlCD", SqlDbType.VarChar).Value = LvlCD
Else
objCommand = New SqlCommand("SELECT DISTINCT LevelCD, Level1 IsChecked, LevelCD+Level2+'|'+Level1+'|'+CASE WHEN Level3 IS NULL THEN '' ELSE Level3 END ID, Level3 Scheme, ItemNo, SubItemNo2, Descriptions Title FROM i_Menu_Access WHERE LevelCD = #LvlCD AND GroupNo = #lvlOneID AND ItemNo = #lvlTwoID AND SubItemNo1 = #lvl3rdID AND SubItemNo2 <> '0' AND Level3 = #Scheme ORDER BY SubItemNo2", objConn)
objCommand.Parameters.Add("#lvlOneID", SqlDbType.Int).Value = lvlOneID
objCommand.Parameters.Add("#lvlTwoID", SqlDbType.Int).Value = lvlTwoID
objCommand.Parameters.Add("#lvl3rdID", SqlDbType.Int).Value = lvl3rdID
objCommand.Parameters.Add("#LvlCD", SqlDbType.VarChar).Value = LvlCD
objCommand.Parameters.Add("#Scheme", SqlDbType.VarChar).Value = scheme
End If
Dim da As New SqlDataAdapter(objCommand)
Dim dt As New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim child As New TreeNode()
child.Text = dr("Title").ToString().Trim()
child.Value = dr("ID").ToString().Trim()
child.SelectAction = TreeNodeSelectAction.SelectExpand
child.CollapseAll()
parentNode.ChildNodes.Add(child)
Next
End Sub
Well, if you design your data-base correctly then you will need only one function to get & fill nodes at any level. For example, let's say consider a sample database table 'Items' such as
ItemId int NOT NULL PK
ItemText varchar(200)
ParentId int NULL FK
Note that we have put FK on ParentId with the same Items table and that can be NULL indicating root level items. Now, you can get items at any level using query such as
SELECT ItemId, ItemText, ParentId FROM Items WHERE ParentId = #ParentId
When you want to retrieve root level items, pass #ParentId as NULL - get expand any node and get childs, pass the ItemId for that node as ParentId to above query.
You can add your datatables in a Dataset and setup the parent and child relationship in the Dataset.
Here is the complete, clean and optimized code. I wrote comments where necessary
DataTable dtbl1=new DataTable();//parent datatable
DataTable dtbl2=new DataTable();//child datatable
DataSet ds = new DataSet();
ds.Tables.Add(dtbl1);
ds.Tables.Add(dtbl2);
ds.Relations.Add("Children", dtbl1.Columns["dtb1ID"], dtbl2.Columns["dtbl2ID"]);//define parent child relation in dataset
if (ds.Tables[0].Rows.Count > 0)
{
trv.Nodes.Clear();
Int32 count = 0;
foreach(DataRow masterRow in ds.Tables[0].Rows)
{
TreeNode masterNode = new TreeNode((String)masterRow["dtbl1ColumnYouWantToDisplay"], Convert.ToString(masterRow["dtbl1ID"]));
trv.Nodes.Add(masterNode);
foreach (DataRow childRow in masterRow.GetChildRows("Children"))
{
TreeNode childNode = new TreeNode((String)childRow["dtbl2ColumnYouWantToDisplay"], Convert.ToString(childRow["dtb2ID"]));
masterNode.ChildNodes.Add(childNode);
count++;
}
}
trv.ExpandAll();
}