xTMx
xTMx

Reputation: 77

Cannot retrieve the values from multiple selection in 1 Listbox VB.net

I want to retrieve the values of the current selected items in the listbox and whenever the user pick more items,the sum of price of these items will be displayed in a Label ex: the user picks 2 phone names from the listbox and the sum of their price will be displayed in the label (It is working for only the first item the user chooses but ignores everything else selected and it doen't work when the user select an item it only displays the price when i press a button) ,Here is what i tried :

Partial Class PickItems
Inherits System.Web.UI.Page

Dim sum As Integer = 0
Protected Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged

    sum = sum + CInt(ListBox1.SelectedValue)
    Label1.Text = sum.ToString()


End Sub

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    Label2.Text = Request.QueryString("Name").ToString()


End Sub End Class

Here is the Listbox code <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" DataSourceID="SqlDataSource1" DataTextField="PhoneName" DataValueField="PhonePrice"></asp:ListBox>

And here is how the page looks like: enter image description here I will also need to move the selected items from this page to the next page(same as i did with the Request.QueryString("Name....) Any help will be appreciated!

Upvotes: 0

Views: 899

Answers (1)

Sage Pourpre
Sage Pourpre

Reputation: 10323

If you want a sum, you need to loop into each of the selected indices to calculate the sum.

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    sum = 0 'reset sum to 0
    For Each I As Integer In ListBox1.GetSelectedIndices
        Dim CurrentItem As ListItem = ListBox1.Items(I)
        sum += CInt(CurrentItem.Value) 
    Next
End Sub

Please note that for the SelectedIndexChanged event to work, you will need to set the AutoPostback attribute to true for your listbox.

AutoPostBack="True"

Upvotes: 1

Related Questions