简体   繁体   中英

How to get Multiple selected listbox items to another listbox

In my ASP.NET application I have two listboxes, say Listbox1 and Listbox2. Listbox1 having some listitems and which is in Multiple Selection Mode. If I Press the transfer button the selected items in Listbox1 should be moved to Listbox2. I have tried it for Single Selection Move and it works fine. Now I need help for multiselection.

Code for Single Selection

     strItemText = lstAvailableItems.SelectedItem.Text
     iItemCode = lstAvailableItems.SelectedValue
     lstAvailableItems.Items.Remove(New ListItem(strItemText, iItemCode))
     lstSelectedItems.Items.Add(New ListItem(strItemText, iItemCode))

Listbox image

列表框

If I press the > button single selected item will be moved from Available Items listbox to selected items list box. How to do this for multiple selection?

A combination of my original, and @Arman's.

    Dim lstRemoveItem As New List(Of ListItem)

    For Each li As ListItem In lstAvailableItems.Items
        If li.Selected Then
            lstRemoveItem.Add(New ListItem(li.Text, li.Value))    
            ' can't remove from the collection while looping through it       
        End If
    Next

    For Each li As ListItem In lstRemoveItem
        lstSelectedItems.Items.Add(li)       ' add to "selected" items
        lstAvailableItems.Items.Remove(li)   ' remove from the original available items
    Next

Use List. Iterate all items in the listbox and whatever it finds to be selected, add it to the list.

Dim lstRemoveItem As New List(Of ListItem)

For Each _item As ListItem In lstAvailableItems.Items
    If _item.Selected Then
        lstRemoveItem.Add(_item)
        'here, method to add item to the first list.
    End If
Next

For Each _item As ListItem In lstRemoveItem
    lstSelectedItems.Items.Add(_item)
Next

Not exactly what you want, but you can configure the variables easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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