After every postback dropdownlist items repeats - asp.net

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

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.

How to load database content to dynamic TextBox when an item is selected from dynamic DropDownList?

This is my interface, all the asp elements displayed are dynamically created! (Except the header)
Things I perform dynamically:
1. Create row with all those asp elements when page loads or button clicked.
2. I am able to lo populate DropDownList in "Items" column from database when it is created dynamically.
What I want to achieve?:
I want to load 'item code' 'item price' to appropriate text box when the item is selected from the DropDownList.
(Ex: when I click Laptop; it should load its item code and unit price to appropriate text box)
(Sorry for my bad programming approach, I'm beginner to asp.net)
'Page Load function'
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack or Page.IsPostBack Then
GenerateRows(numRows) 'Creates dynamic Table row and column with TextBox and DropDownList'
End If
End Sub
'Dynamic generating function, i have trimmed the code, to make it simple'
Protected Sub GenerateRows(numRows As Integer)
For i = 0 To numRows
Dim tRow As New TableRow
Dim tCode As New TableCell
Dim tItem As New TableCell
Dim lCode As New TextBox
Dim dList As New DropDownList
con = New Data.SqlClient.SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=DataStore;Integrated Security=True")
con.Open()
query = "Select Item_Desc from Product"
cmd = New Data.SqlClient.SqlCommand(query, con)
cmd.ExecuteNonQuery()
dList.DataSource = cmd.ExecuteReader
dList.DataTextField = "Item_Desc"
dList.DataBind()
dList.Items.Insert(0, New ListItem("--- Select Product ---"))
dList.Height = 30
dList.AutoPostBack = True
dList.CausesValidation = True
AddHandler dList.SelectedIndexChanged, AddressOf Dynamic_Method
con.Close()
tCode.Controls.Add(lCode)
tItem.Controls.Add(dList)
tRow.Cells.Add(tCode)
tRow.Cells.Add(tItem)
Table1.Rows.Add(tRow) 'Table1 is not dynamic element'
Next
numRows += 1
ViewState("RowCount") = numRows 'numRows is Global variable'
End Sub
'This function is called when the selected index of DropDownList changes'
Protected Sub Dynamic_Method(ByVal sender As Object, ByVal e As EventArgs)
con = New Data.SqlClient.SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=DataStore;Integrated Security=True")
con.Open()
Dim DDL As DropDownList = DirectCast(sender, DropDownList)
query = "Select * from Product where Item_Desc='" & DDL.SelectedValue.ToString & "'"
cmd = New Data.SqlClient.SqlCommand(query, con)
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While (dr.Read)
ic = dr(0) 'dr(0) contains Item code of selected value which i need to add to textbox'
End While
End If
con.Close()
End Sub

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

Resources