Vb.Net ASP.Net Shopping Cart with cookies - asp.net

I am building an E-commerce website and everything went great until I started thinking about how I'm going to make my shopping cart, using cookies.
I'm using a datalist to display my products, when a user clicks on a button, I want the product ID to be stored in a cookie so when the user goes to his shopping cart, the cart checks all the ID's in the cookie and then checks in my access database which product it should add.
Does anyone know how I should make this work or have a useful tutorial? Because all the tutorials I found are in java, php, c# etc. but I need to make this in vb.net because it's a school project.
Thanks in advance!

Protected Sub Button1_Click(sender As Object, e As EventArgs)
Dim btnShoppingCart As Button = TryCast(sender, Button)
'get values from datalist
Dim datalistItem As DataListItem = DirectCast(btnShoppingCart.NamingContainer, DataListItem)
'productId
Dim lblProductId As Label = DirectCast(datalistItem.FindControl("lblProductId"), Label)
Dim strProductId As String = lblProductId.Text
Dim objCookie As New HttpCookie("ShoppingCart")
objCookie.Value = strProductId
objCookie.Expires = Now.AddDays(30)
Response.Cookies.Add(objCookie)
End Sub
End Class
If I do it like this, I just get one value saved in the cookie, any way to get multiple values?
If I would use objCookie.Values.add("ID", strProductId) I can only save 1 ID to it, right?

If Request.Cookies("Winkelmand") Is Nothing Then
Dim objCookie As New HttpCookie("Winkelmand")
objCookie.Values.Add(strProductId, strProductId)
objCookie.Expires = Now.AddDays(30)
Response.Cookies.Add(objCookie)
Else
Dim objCookie As HttpCookie = Request.Cookies("Winkelmand")
Dim strControleDubbel As String
strControleDubbel = objCookie.Values.Item(strProductId)
If strControleDubbel = Nothing Then
objCookie.Values.Add(strProductId, strProductId)
Response.Cookies.Add(objCookie)
End If
This code worked!

Related

Can't update data when value is assigned to textboxes in load page

My problem is probably stupid due to my inexperience to programming but please help.
So, I set some textboxes to values from my other page so the user can edit their Task and see what their task was original and edit from there.
The problem is that I set those values in Page Load so when I tried to update it, it updated the original value not the new one that entered because the page load return the old value. Because of this I cannot update my database to new value.
Is there anyway to approaches this problem or to fix this? Like should I place the code somewhere else?
Edit: Ok so I did some more research and found that my problem could maybe be solved by using IsPostBack but I don't understand how to use this code. The only thing I kinda understand is that it is used to return the page to before it got refresh by page load?
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("Editing") IsNot Nothing Then
btnCreate.Visible = False
btnEdit.Visible = True
Dim Form As FormViewRow = CType(Session("Editing"), FormViewRow) 'get data from the the formview in Home page
Dim Title As Label = CType(Form.FindControl("TitleLabel"), Label)
txtTitle.Text = Title.Text
Dim description As Label = CType(Form.FindControl("DescriptionLabel"), Label)
txtDescription.Text = description.Text
Dim diff As Label = CType(Form.FindControl("DifficultyLabel"), Label)
ddlDifficulty.Text = diff.Text
Dim taskID As Label = CType(Form.FindControl("IDLabel"), Label)
Dim whatID As String = taskID.Text
Session("EditTaskID") = taskID.Text
End If
End Sub
Ok so I was just playing around with IsPostBack and managed to get it to work.
All I did was put my code in an If statement IsPostBack is not equal True Then... Since I'm still learning can someone explain the meaning of IsPostBack in the simplest terms?
It's fine if no one explain it to me. My problem is solved and thank you Amin for taking your time trying to help me. (:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If IsPostBack <> True Then
If Session("Editing") IsNot Nothing Then
btnCreate.Visible = False
btnEdit.Visible = True
Dim Form As FormViewRow = CType(Session("Editing"), FormViewRow) 'get data from the the formview in Home page
Dim Title As Label = CType(Form.FindControl("TitleLabel"), Label)
txtTitle.Text = Title.Text
Dim description As Label = CType(Form.FindControl("DescriptionLabel"), Label)
txtDescription.Text = description.Text
Dim diff As Label = CType(Form.FindControl("DifficultyLabel"), Label)
ddlDifficulty.Text = diff.Text
Dim taskID As Label = CType(Form.FindControl("IDLabel"), Label)
Dim whatID As String = taskID.Text
Session("EditTaskID") = taskID.Text
End If
End If
End Sub
I don't know whether your editing page is opened in the same window or a new one. In first scenario, you can save edited values somewhere like Session and restore them in main page's Page_Load server event. According to 2nd scenario, you can use some simple javascript codes to reflex data changes to main page.

How can I save a image in a session variable and then display in asp.net and sqlserver

I' m new in this, also I'm new in Visual Basic and Sql Server, and I'm Chile...
Well, I have a question, I've been thinking for several days and can not solve.
I need to show an image in a web form of a client when he wants to see your information.
For that, I have the next sources:
Table Client
email(varchar), nameClient(varchar), nameImage(varchar)
Table Image
nameImage(varchar), image(image)
I have the next proc:
select c.email, c.nameClient, i.image
from Client as c join Image as i on c.nameImage=i.nameImage
In asp.net, I have a web Form as VerCliente.aspx, and in VerCliente.aspx.vb I have this:
Partial Class Default19
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
MostrarNombreCliente.Text = Session("correo")
End Sub
Protected Sub BotonMostrarPerfil_Click(sender As Object, e As EventArgs) Handles BotonMostrarPerfil.Click
Dim numero As Integer
Dim dvSql As Data.DataView = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), Data.DataView)
'of this way I do the connection to BD'
If dvSql.Count > 0 Then
numero = 1
'to display the information in the textbox Iam occupying session variables'
Session("email") = dvSql(0).Item(0)
MostrarEmail.Text = Session("email")
Session("nombre") = dvSql(0).Item(1)
MostrarNombreCompleto.Text = Session("nombre")
in VerCliente.aspx I have this , and I would display the image on it
asp:Image ID="MostrarImagen" runat="server" Height="191px" Width="270px" /
but I dont know how to occupy session variables here
MostrarImagen.ImageUrl....(I dont know How )
I tried this but it does not work
Session("imagen") = dvSql(0).Item(2)
MostrarImagen.ImageUrl.ImageUrl = Session("imagen")
End If
End Sub
End Class
thank....bye!!!
Well, after of I'm trying many times, finally I can to resolve my problem, howerer I think that the way that I did the new solution is quite different to how I had posed my problem, but the important is that my solution works fine...
Here is my solution, I hope that can to be of utility for you..
Thank for your comments!!!
Session("imagen") = dvSql(0).Item(8)
If (Context.Session("imagen")) IsNot Nothing Then
Dim image As Byte() = DirectCast(Context.Session("imagen"), Byte())
Dim base64String As String = Convert.ToBase64String(image, 0, image.Length)
Image1.ImageUrl = Convert.ToString("data:image/png;base64,") & base64String
Image1.Visible = True
End If

Filling the dropdown from sql bug

Good afternoon people have been trying to fill a dropdown using a sql command, until so good, when I click on the dropdown it shows all the items, but when I try to click on an item in the dropdown it always returns the first item in the dropdown .... follows the codes, what i want to do is get the selected value and item from the dropdown and save it on a label for future use.
I appreciate all the support possible,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
utilizador.Text = Me.Context.User.Identity.Name
If (Not Page.IsPostBack) Then
escolhePerfil()
End If
'DropDownPerfil.DataBind()
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
Function escolhePerfil() As Boolean
Dim connstring As String = "Data Source=10.2.24.17;Persist Security Info=True;User ID=sa;Password=Pr0dUn1C0$qL;database=ePrimavera"
Dim SQLData As New System.Data.SqlClient.SqlConnection(connstring)
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT u.WindowsUser,u.Email ,g.Description, u.Login FROM [ePrimavera].[dbo].[PLT_Users] as u,[ePrimavera].[dbo].[PLT_UserGroups] as ug, [ePrimavera].[dbo].[PLT_Groups] as g where u.ID = ug.UserID And ug.GroupID = g.ID and u.WindowsUser like 'bancounico\" & utilizador.Text & "'", SQLData)
SQLData.Open()
Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
If dtrReader.HasRows Then
DropDownPerfil.DataValueField = "Login"
DropDownPerfil.DataTextField = "Description"
DropDownPerfil.DataSource = dtrReader
DropDownPerfil.DataBind()
End If
SQLData.Close()
Return True
End Function
.aspx
<asp:DropDownList ID="DropDownPerfil" runat="server"
Height="16px" Width="202px" CssClass="DropBorderColor">
</asp:DropDownList>
try the following code:
Protected Sub DropDownPerfil_SelectedIndexChanged(sender As Object, e As EventArgs)
lbperfil2.Text = DropDownPerfil.SelectedItem.Text
lbnome.Text = DropDownPerfil.SelectedValue
End Sub
The problem is that you are trying to get the value "too early". The value is not valid in the Page_Load, since the control's OnLoad event fired after the Page's OnLoad (Page_Load) event.
The way, what the others wrote the correct, since the Event handlig section (inclueding control's onchanged event) will process after the Load section.
For more details check the offical ASP.NET life cycle site in the MSDN
The likely reason is that some (if not all) the values you are assigning to the DropDownList for Login are occur more than once.
When you then select an item in the DDL, if the value of that item occurs more than once, the selected index will highlight the first instance. To test this, comment out DropDownPerfil.DataValueField = "Login"
I am sure upon selection, it will highlight the correct item you intended on selecting.

asp.net onClick event for Button

I have a button on a web page that when clicked connects to my SQL server and runs a stored procedure. The buttons works fine (It simply pushes data into a database table).
I’m new to .NET programming and I’m having trouble finding the right code ideas to add on to the current code for the button I already have.
Ideally, I would just like to have a message box to appear when the button is clicked to notify the user that the ‘data has been saved’ with just the "OK" option and for the user to then be redirected to the home page.
I also need to make sure that this button is only pressed once or deactivated once it has been pressed that day as I don’t want the user to press the button multiple times.
Here is my current code for the button:
Protected Sub btnAddRawData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddRawData.Click
'database conn, this is linked to the web config file .AppSettings
Using dbconnection As New SqlConnection(ConfigurationManager.AppSettings("dbconnection"))
dbconnection.Open()
'command to state the stored procedure and the name of the stored procedure
Using dbcommand As SqlCommand = dbconnection.CreateCommand
With dbcommand
.CommandType = CommandType.StoredProcedure
.CommandText = "GasNominationsRawData_Insert"
'simply execute the query
dbcommand.ExecuteNonQuery()
'I need to add some code for the button here and...
'redirect to the main home page
Response.Redirect("~/default.aspx?")
End With
End Using
End Using
End Sub
Any ideas and suggestions would be much appreciated.
Regards,
Betty.
function success()
{
alert('Your data has been saved successfully)';
window.location.href='Default.aspx';
}
On code behind, right after this line:
dbcommand.ExecuteNonQuery()
Do this:
Dim cs As ClientScriptManager = Page.ClientScript
Dim csname1 As [String] = "PopupScript"
Dim cstype As Type = Me.[GetType]()
Dim cstext1 As New StringBuilder()
cstext1.Append("success();")
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString())

Populate text boxes with data based on redirect from another page

This task is a little out of my reach so i dont even really know where to start...
I want a user to click the command field "select" in my gridview. I then want them to be redirected ( response.redirect()) to an input form that will have its various asp.net text boxes filled with data from that selected item.
I also need the ability to do this logical process:
IF the form is loaded from user
selecting item in gridview THEN
''Populate controls with data from selected gridview item Else Load
form as normal and have the controls
blank endif
I was suggested to use this command for the redirect load...Not sure if its correct:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If InStr(Request.ServerVariables("HTTP_REFERER"), "LogViewer.aspx") Then
'FILL the text boxes with the data from data source!
End If
End Sub
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
EDIT
I got it working thanks to A Tuliper...now how can i get my drop down list to select the correct item based on the data in the gridview??
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connection As New SqlConnection("My Connection ")
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * from AppMaster WHERE RecNum = #recnum", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#recnum", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
NameTxt.Text = dt.Rows(0)("UserName").ToString()
'''''''''this drop down list needs to be the correct item'''''''''''''''''
'AppDropDownList.SelectedValue = dt.Rows("Application").ToString()
SelectedDateTxt.Text = dt.Rows(0)("DateOfChange").ToString()
DescriptionTxt.Text = dt.Rows(0)("Description").ToString()
SnipetTxt.Text = dt.Rows(0)("Snippet").ToString()
End If
connection.Close()
End Sub
The easiest unhacky method here is to simply create a link in your gridview with the parameters in the URL going to say:
Details
And then in your second page read them:
string param1 = Request.QueryString["Param1"]; //or whatever its called - change it of course

Resources