简体   繁体   English

无法从1个列表框VB.net中的多个选择中检索值

[英]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 : 我想检索列表框中当前选定项目的值,并且每当用户选择更多项目时,这些项目的价格之和就会显示在Label ex中:用户从列表框中选择2个电话名称,它们的价格将显示在标签中(仅适用于用户选择的第一个项目,但会忽略其他所有选定内容,当用户选择一个项目时,它仅在按下按钮时显示价格,因此无效)我尝试过的是

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> 这是列表框代码 <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" DataSourceID="SqlDataSource1" DataTextField="PhoneName" DataValueField="PhonePrice"></asp:ListBox>

And here is how the page looks like: 这是页面的外观: 在此处输入图片说明 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! 我还需要将选定的项目从此页面移至下一页(与我对Request.QueryString(“ Name .......”所做的操作相同),将不胜感激!

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. 请注意,要使SelectedIndexChanged事件起作用,您需要将列表框的AutoPostback属性设置为true。

AutoPostBack="True"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM