Program won't give me the right Sum - asp.net

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

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

After every postback dropdownlist items repeats

I have bind my dropdownlist with database. But on each PostBack the items in dropdownlist gets repeat again.
e.g.
OnPage Load I have this items in dropdownlist 1,2,3,4.. etc Now suppose page gets postBack then it looks like 1,2,3,4,1,2,3,4
Vb code
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateAreas()
End Sub
Private Sub PopulateAreas()
If IsPostBack Then
Dim citySelector As DropDownList = 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("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
UPDATE
I have master page which has dropdownlist of cities. I am using masterpage control to mycontent page like below.
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Now in my PopulateArea() class there is query in which WHERE clause have cityselector. So according to city my area gets fetched.
Call your function inside not postback event so that the dropdown is not called on postback events(which fills it everything).
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
if ispostback = false then
Me.PopulateAreas()
end if
End Sub
its pretty simple.. the page load event is triggered every time anything is post back.
use this
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
//do stuff when post back occurs
Else
Me.PopulateAreas() //put this function here so that it executes only once
End If
End Sub
If your dropdown values have to change on the postback. Say initially the values where 1,2,3,4 and on postback if the values has to be 2,3,4,5 based on some of the values you change on the form controls you will have to clear the dropdown values first and then add new values to it.
areasList.Items.Clear()
Also see that AppendDataBoundItems is not true: in your .aspx page
Change your code to,
Private Sub PopulateAreas()
If IsPostBack Then
areasList.Items.clear()
Dim citySelector As DropDownList = 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("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
End Sub

Invalid attempt to call Read when reader is closed

I'm attempting to create a search page, which will display the results into a Gridview, but keep getting the following error when I click the my search button: Invalid attempt to call Read when reader is closed.
This is my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As [String] = ConfigurationManager.ConnectionStrings("myDbConnectionString1").ConnectionString
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim mySQLQuery As String
Dim vID As String
vID = Request.QueryString("pgResults")
mySQLQuery = "SELECT name,address,results,url FROM myTb WHERE name LIKE '%" + TextBox1.Text + "%'"
Dim myCommand As New SqlCommand(mySQLQuery, connection)
Dim myReader1 As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
While (myReader1.Read())
GridView1.DataSource = myReader1
GridView1.DataBind()
End While
panelBody.Visible = False
panelSearchResults.Visible = True
connection.Close()
End Sub
Could I get some help please?
You cannot call Read() and then use a IDataReader as a DataSource, let DataBinding handle that. try this:
Dim myReader1 As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
GridView1.DataSource = myReader1
GridView1.DataBind()

Value in textbox is always the same on update statement

I select values from database into textboxes on page load. Then when I change them and want to update the database, values are same as original values. For example I select name Robin Hood into TextBoxName, change it to Bill Gates, but the value of textbox on updating is still Robin Hood. How can I fix this behavior?
However this applies only to textboxes with TextMode="SingleLIne" Or "MultiLine". When textbox has TextMode="Url" for example, it works fine.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Bind
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT * FROM Profiles WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
Dim rd As SqlDataReader = cmd.ExecuteReader()
While rd.Read()
ProfileImage.ImageUrl = rd.Item("ProPicUrl")
txtName.Text = rd.Item("Name")
txtCity.Text = rd.Item("City")
drpRegion.Items.FindByText(rd.Item("Region")).Selected = True
txtAge.Text = rd.Item("Age")
RadioButtonList1.Items.FindByText(rd.Item("Sex")).Selected = True
txtLink.Text = rd.Item("Link")
txtPhone.Text = rd.Item("Phone")
txtAbout.Text = rd.Item("About")
txtMotto.Text = rd.Item("Motto")
txtGoal.Text = rd.Item("Goal")
txtHobby.Text = rd.Item("Hobby")
End While
conn.Close()
End Using
Catch ex As Exception
End Try
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim fileUrl As String = "~/ProPics/"
Dim name As String = txtName.Text
Try
'Save profile picture
Try
If FileUpload1.HasFile Then
fileUrl += FileUpload1.FileName
FileUpload1.SaveAs(Server.MapPath(fileUrl))
Else
fileUrl = ProfileImage.ImageUrl
End If
Catch ex As Exception
UploadMessage.Text = "Nastala chyba při nahrávání obrázku." + vbCrLf + "Chybové hlášení: " + ex.Message
End Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "UPDATE Profiles SET Name = #Name, ProPicUrl = #Url, City = #City, Region = #Region, Age = #Age, Sex = #Sex, Link = #Link, Phone = #Phone, About = #About, Motto = #Motto, Goal = #Goal, Hobby = #Hobby WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#Url", fileUrl)
cmd.Parameters.AddWithValue("#Name", name)
cmd.Parameters.AddWithValue("#City", txtCity.Text)
cmd.Parameters.AddWithValue("#Region", drpRegion.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Age", txtAge.Text)
cmd.Parameters.AddWithValue("#Sex", RadioButtonList1.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text)
cmd.Parameters.AddWithValue("#Link", txtLink.Text)
cmd.Parameters.AddWithValue("#About", txtAbout.Text)
cmd.Parameters.AddWithValue("#Motto", txtMotto.Text)
cmd.Parameters.AddWithValue("#Goal", txtGoal.Text)
cmd.Parameters.AddWithValue("#Hobby", txtHobby.Text)
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Refresh page
Response.Redirect(Request.RawUrl)
End Using
Catch ex As Exception
End Try
End Sub
You need to add a check for IsPostBack property of the page when you execute code in the Page_Load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
if Not PostBack Then
...... code to execute only the first time the Page_Load is called
Try
End Try
Catch ex As Exception
End Try
End If
.. code to execute every time....
End Sub
When your user clicks on a button with Runat=Server then the button calls the event on the server side code, but this cause a new call to Page_Load.
Actually your code reloads from the database the original value everytime the Page_Load event executes and thus your button click event code sees the original value from the database instead of the modified value.
This article on the Page Life Cycle could be useful here

Populating dropdownlist on pageload event

I can't see why this is not working.
I have a dropdownlist named ddlRoomName and a SQL table named roomlist.
When i run the SQL command in SQL editor it works fine. But when I load the page the rooms do not load!
Am i missing something obvious here?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
ddlRoomName.Items.Clear()
ddlRoomName.Items.Add(New ListItem("--Select Room--", ""))
ddlRoomName.AppendDataBoundItems = True
Dim strConnString As String = ConfigurationManager.ConnectionStrings("a_cisco").ConnectionString
Dim strQuery As String = "Select * from roomlist"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
ddlRoomName.DataSource = cmd.ExecuteReader()
ddlRoomName.DataTextField = "RoomName"
ddlRoomName.DataValueField = "intRoom"
ddlRoomName.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
End If
End Sub
You are only loading them on a postback. Is it really what you want? Maybe you want:
If Not Page.IsPostBack Then
End If
(then the ViewState will keep the items in the DropDownList in a postback)

Resources