There are examples here on Stackflow on how to add ListBox items to the session and then repopulate the items back to the ListBox but for some reason it is not working.
Here's the code snippet
Private Sub btnSelect_Click(sender As Object, e As EventArgs) Handles btnSelect.Click
If lstFields.SelectedIndex >= 0 Then
For i As Integer = 0 To lstFields.Items.Count - 1
If lstFields.Items(i).Selected Then
If Not arrayFields.Contains(lstFields.Items(i)) Then
arrayFields.Add(lstFields.Items(i))
Session("items") = arrayFields
End If
End If
Next
For i As Integer = 0 To arrayFields.Count - 1
If Not lstSelected.Items.Contains((CType(arrayFields(i), ListItem))) Then
lstSelected.Items.Add((CType(arrayFields(i), ListItem)))
End If
lstFields.Items.Remove((CType(arrayFields(i), ListItem)))
Next
lstSelected.SelectedIndex = -1
End Sub
When I try to repopulate the items back to ListBox using the For Each loop, the error I kept getting using VS 2015 that shows:
An exception of type 'System.InvalidCastException' occurred in FocusVB.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.WebControls.ListBox' to type 'System.Collections.IEnumerable'.
Here's the snippet of the for each loop:
For Each item As ListItem In Session("item")
lstSelected.Items.Add(New ListItem(item.Text, item.Value))
Next
Am I missing somewhere in the code?
2 Answers
Just remove ListItem from the line For each item as listitem ..
For Each item In Session("item")
lstSelected.Items.Add(New ListItem(item.Text, item.Value)) Next
Don't ask me why ,rather read this .Take a look at the namespace of it,it'll answer you(if you are not talking about System.Windows.Documents.listItem)
Your enumerated list contains Session("items") = arrayFields
However, your reference is item, not items. Change to items.
If Not Session("items") Is Nothing Then
For Each item As ListItem In Session("items")
lstSelected.Items.Add(New ListItem(item.Text, item.Value))
Next
End If