Thursday 14 July 2016

Move multiple items from one ListBox to another ListBox ASP.NET

Adding multiple items from one ListBox to another seems like a trivial thing. Lets say you want to generate a report, but you are only able to add 1 item at a time from one ListBox to another. Wouldn't that just be a waste of time?



Below is a code snippet that iterates through your first ListBox and then adds it to the second, ensuring no duplicates are being added.


Firstly, make sure SelectionMode is set to Multiple on your ListBox.

Now you add the code to the button or whichever event triggers the move from the one ListBox to the Other.

lstChooseFields is the "from" Listbox and lstSelectedFields is the "to" Listbox

  'An item must be selected
  If lstChooseFields.SelectedIndex > -1 Then
      Dim selectedItems = From i In lstChooseFields.Items Where i.Selected Select i
      For Each item In selectedItems
          'Do not add duplicates
          If lstSelectedFields.Items.FindByValue(item.Value) Is Nothing Then
              lstSelectedFields.Items.Add(item)
          End If
      Next
  End If

No comments:

Post a Comment