Incrementing a variable in VB.net with a button - asp.net

I'm trying to increment my variable on a button click. It increments only once. It seems as though it's getting lost when it reloads the page.
I'm using the following code:
Dim ItemSelect As New ArrayList()
Dim Quantities As New ArrayList()
Dim itemQtyOrdered As Integer
Public Sub ShtickDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ShtickDataList.ItemCommand
If e.CommandName = "ViewCart" Then
Response.Redirect("~/ShoppingCart.aspx")
End If
If e.CommandName = "addToCart" Then
Dim itemQuantity As DropDownList = e.Item.FindControl("QuantityDropDown")
itemQtyOrdered = itemQuantity.SelectedValue
ItemSelect.Add(e.CommandArgument)
Quantities.Add(itemQtyOrdered)
Session("itemInCart") = ItemSelect
Session("quantities") = Quantities
viewInvoice()
End If
End Sub
Protected Sub viewInvoice()
Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection2)
comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = #ProductID", conn)
Dim i As Integer
For i = 0 To ItemSelect.Count - 1
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = ItemSelect(i)
Next
Try
conn.Open()
reader = comm.ExecuteReader()
ViewCartlink.Text = "View Cart: (" & ItemSelect.Count & ")"
Finally
conn.Close()
End Try
End Sub

Ah, you may be referring to ItemSelect and Quantities lists. You need to look for them in Session and only create them if they are not in the Session. I am rusty on VB.NET, so this is C# version. In Page_Load:
ItemSelect = (ArrayList)Session["itemInCart"];
if (ItemSelect == null)
{
ItemSelect = new ArrayList();
Session["itemInCart"] = ItemSelect;
}
and the same for Quantities.
Also, your loop in viewInvoice method is wrong. For more than one item in ItemSelect list you are adding multiple parameters with the same name. You probably only wanted to do it once with
comm.Parameters("#ProductID").Value = ItemSelect(ItemSelect.Count - 1)

Related

asp.net DropDownList postback not executing method on first postback

I'm facing very un natural problem suddenly. I have DropDownList with autopostback is true. Postback executes a method which populates other things onpage according to selection. Now When I select any value first time from that dropdown then page gets postback but nothing get populate but from second time it works fine. Even I put breakpoint on that dropdown & it's not even hitting breakpoint for first postback.
<asp:DropDownList ID="ClientCode" runat="server" ClientIDMode="Static" CssClass="field-pitch" AutoPostBack="true"></asp:DropDownList>
Private Sub ClientCode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ClientCode.SelectedIndexChanged
Me.populateConsignerDetails()
End Sub
Private Sub populateConsignerDetails()
Try
Dim str As String = "SELECT * FROM clientsDetails WHERE clientID = #clientID"
con.Open()
Dim cmd As New MySqlCommand(str, con)
cmd.Parameters.AddWithValue("#clientID", ClientCode.SelectedItem.ToString)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
Dim payingParty As String = String.Empty
If dt.Rows.Count > 0 Then
consignerName.Text = dt.Rows(0)("clientName").ToString
consignerAddress.Text = dt.Rows(0)("companyAddress").ToString
consignerMobile1.Text = dt.Rows(0)("contactNumber1").ToString
consignerCity.Text = dt.Rows(0)("city").ToString
consignerState.Text = dt.Rows(0)("state").ToString
consignerPinCode.Text = dt.Rows(0)("pinCode").ToString
End If
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Update
Private Sub myadmin_shipment_details2_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
populateClient()
End If
End Sub
Private Sub populateClient()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from clientsDetails where status = 'active'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("clientID").ToString()
item.Value = sdr("ClientName").ToString()
ClientCode.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub

Program won't give me the right Sum

I want to get the sum of the selected items in the listbox and display them in a label but i am always getting 0,i also want to put the selected items in another label too which is also not working.
Here is what the code look like:
Dim sum As Integer
Dim Items1 As String = "None"
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim sql As String
connetionString = "Data Source=.;Initial Catalog=Shop;integrated security=true"
sql = "select PhoneName,PhonePrice from SmartPhones"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ListBox1.DataSource = ds.Tables(0)
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
code where the display should happen:
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles TotalPrice.Click
sum = 0 'reset sum to 0
For Each i As Integer In ListBox1.GetSelectedIndices
Dim CurrentItem As ListItem = ListBox1.Items(i)
sum = sum + CInt(CurrentItem.Value)
Items1 = Items1 + " , " + CStr(CurrentItem.Text)
Next
Label3.Text = Items1
Label1.Text = sum
End Sub
Here is the page Design and the Page On the web Respectively:
PhoneName is of type varchar in database & PhonePrice is of type integer (Both Filled correctly).
ListBox code:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" ></asp:ListBox>
What's the reason that the code won't give me the desired result?
What is happening is that when you click TotalPrice a postback is performed (What is a postback?). If you look at the ASP.NET page lifecycle you will see that the Load event happens before the postback event handling (e.g. your Sub Button2_Click).
So, you click the button, it runs the Me.Load handler and... your list is reset before the click handler gets a chance to run.
There is a property you can check to see if the page is running as a result of a postback: Page.IsPostBack.
So all you need to do is check it to see if you need to populate the list:
Sub FillItemsList()
Dim connectionString As String = "Data Source=.;Initial Catalog=Shop;integrated security=true"
Dim dt As New DataTable()
Using connection As New SqlConnection(connectionString)
Dim sql As String = "SELECT PhoneName,PhonePrice FROM SmartPhones"
Using adapter As New SqlDataAdapter(sql, connection)
adapter.Fill(dt)
End Using
End Using
ListBox1.DataSource = dt
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
If Not Page.IsPostBack Then
FillItemsList()
End If
End Sub

Create dropdownlist based on selected dropdownlist from master page

I have masterpage & content page. In master Page I have DropDownList of Cities which Gets cities from database. And in my content page I DropDownList Of Areas which also comes from database. Now Suppose If My city gets changed then desire area related to that particular selected city should also get changed. I have manage my db tables properly & passing correct query as well. But DropDownList Of areas doesn't gets refreshed if City DropDownList gets changed. Following code I am trying.
MasterPage
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateCities()
If Not IsPostBack Then
If Session("masterLocation") Is Nothing Then
Session("cityName") = "Pune"
Else
locationSelector.Text = Session("masterLocation").ToString()
End If
End If
locationPopupActivator.Text = locationSelector.SelectedValue.ToString
End Sub
Private Sub PopulateCities()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select cityName from cities where status = 'active' order by cityName"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("cityName").ToString()
item.Value = sdr("cityName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
locationSelector.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
ContentPage
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
If Not IsPostBack Then
Me.PopulateAreas()
End If
End Sub
Private Sub PopulateAreas()
areasList.Items.Clear()
Dim citySelector As RadioButtonList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
areasList.Items.Insert(0, New ListItem("All Area", "All"))
End Sub
Everything in your code is fine just make changes On Pre_Render event of your content page
If IsPostBack Then
Me.PopulateAreas()
End If
Make this changes. Hope this will solve your problem.

Exiting out of sub if result of query to database is DbNull

I have an edit profile page where the user can edit their profile information. At the minute, new users cannot use this page as they have not got a corresponding record in the 'userprofiles' table. I am using the aspnet_ membership system with corresponding aspnet_User tables in the same database. There is no link between 'userprofiles' and the aspnet tables
I have a sub called 'DisplayData()' that checks if there is a record for the user in the table and displays their profile information in the textboxes. Unfortunately, for new users, there is no record in the table so it throws an error
Here is my Page_Load sub:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("userName") = User.Identity.Name
Dim conn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
conn.Open()
Dim cmdcheck As New OleDbCommand("SELECT TravellerName FROM userprofiles WHERE (TravellerName = ?) ", conn)
cmdcheck.Parameters.AddWithValue("#userName", Session("userName"))
Dim profileCheckDr = cmdcheck.ExecuteReader()
If IsDBNull(profileCheckDr("TravellerName")) Then
??
End If
If Not IsPostBack Then
DisplayData()
savec.Visible = False
End If
End Sub
And here is my DisplayData() function which inputs all current user profile information into the textboxes on the page:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim newEmailAddress = ""
Dim newDescription = ""
Dim newDOB = ""
Dim newLocation = ""
Dim newProfession = ""
Dim newSmoker = ""
Dim newDrinker = ""
Dim newEducationLevel = ""
Dim newMaritalStatus = ""
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
If Not IsDBNull(profileDr("EmailAddress")) Then newEmailAddress = profileDr.Item("EmailAddress")
If Not IsDBNull(profileDr("DOB")) Then newDOB = profileDr.Item("DOB")
If Not IsDBNull(profileDr("Location")) Then newLocation = profileDr.Item("Location")
If Not IsDBNull(profileDr("Description")) Then newDescription = profileDr.Item("Description")
If Not IsDBNull(profileDr("Profession")) Then newProfession = profileDr.Item("Profession")
If Not IsDBNull(profileDr("Smoker")) Then newSmoker = profileDr.Item("Smoker")
If Not IsDBNull(profileDr("Drinker")) Then newDrinker = profileDr.Item("Drinker")
If Not IsDBNull(profileDr("EducationLevel")) Then newEducationLevel = profileDr.Item("EducationLevel")
If Not IsDBNull(profileDr("MaritalStatus")) Then newMaritalStatus = profileDr.Item("MaritalStatus")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
description.Text = newDescription
email.Text = newEmailAddress
smoker.SelectedValue = newSmoker
drinker.SelectedValue = newDrinker
dd_userlocation.SelectedValue = newLocation
dob.Text = newDOB
educationlevel.SelectedValue = newEducationLevel
profession.SelectedValue = newProfession
maritalstatus.SelectedValue = newMaritalStatus
conn.Close()
End Sub
How do I break out of the Page Load sub so that the DisplayData() sub doesn't run if the results of the query in the Page Load sub do not return anything. I've already tried using 'Exit Sub' but it doesn't seem to work.
A quick fix would be to simply move your If statement to surround the call to DisplayData:
If Not IsPostback Then
If Not IsDBNull(profileCheckDr("TravellerName")) Then
DisplayData()
End If
End If
However, the real question is - if the user has not registered for your site yet, how are they even able to get to the Edit Profile page? Unregistered users should not be able to get to user-specific parts of your site.

Object reference not set to an instance of an object. splitItems(0).toString

i have this button which i add in row of data however, it give me error, can anyone help me out tell me why is the splitItems(0).ToString cause error, how should i get that value to store in the database
Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
Dim rowIndex As Integer = 0
Dim sc As New StringCollection()
If ViewState("CurrentTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count < 10 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
'extract the TextBox values
Dim box5 As TextBox = DirectCast(Gridview3.Rows(rowIndex).Cells(1).FindControl("TextBox5"), TextBox)
'get the values here
Dim box6 As Date
box6 = Convert.ToDateTime(box5.Text)
Dim box7 As Date = Convert.ToDateTime(box5.Text)
sc.Add(box6)
rowIndex += 1
Next
InsertRecords(sc)
End If
Else
' lblMessage.Text = "Cannot save as there no information recorded"
MsgBox("failed")
End If
End Sub
Protected Sub InsertRecords(sc As StringCollection)
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
End If
Next
Try
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("mydatabase").ConnectionString
Dim cmd As String
cmd = "Insert into Date values (#date) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
//error found at this line splitItems(0).ToString()
myCmd.Parameters.Add(New SqlParameter("#date", splitItems(0).ToString()))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
End Sub
Please check with the breakpoint and make sure splitItems has more than one values.
You will probably find that either there are no elements in the splitItems array, or the element splitItem(0) equals "Nothing".
Just briefly looking at your code I wonder if the main problem is in the ForEach at the top of InsertRecords. I think if sc = {"1/1/2010"} then the "If item.contains(",")" will never be true so the date will never be added to the splitItems array. A.K.A the splitItems array would be empty when it hits the ToString line that is throwing the exception.

Resources