Hi,
I've got a list box on a web form which, when loaded, uses data from a text field in a database to determine which values should be selected. When the user presses save, the selections from the list box should be resaved to the text field.
This works fine if the user manually selects items from the list box, but if they don't make any changes and the list box shows just the selected items from the loading code then, when the user tries to resave, the selectedindex of the list box is showing as 0, even though the items are highlighted, so resave doesn't work.
Here's the code:
Thanks in advance.
I've got a list box on a web form which, when loaded, uses data from a text field in a database to determine which values should be selected. When the user presses save, the selections from the list box should be resaved to the text field.
This works fine if the user manually selects items from the list box, but if they don't make any changes and the list box shows just the selected items from the loading code then, when the user tries to resave, the selectedindex of the list box is showing as 0, even though the items are highlighted, so resave doesn't work.
Here's the code:
Code:
'Firstly to select values from the list box
If Not DataReader.GetValue(119) Is DBNull.Value Then
'firstly get the values
Dim fullString As String = DataReader.GetValue(119)
'check if there is a comma separator in the string, if not then there's only one
'value, so use that
If InStr(fullString, ",") = 0 Then
Me.AdditionalEmailList.SelectedValue = fullString
'otherwise we need to get each of the values by looping through the string
Else
Dim charPosition As Integer
Dim listName As String
While fullString <> ""
If InStr(fullString, ",") = 0 Then
charPosition = fullString.Length
Else
charPosition = fullString.IndexOf(",")
End If
listName = Left(fullString, charPosition)
fullString = fullString.Remove(0, charPosition)
If fullString <> "" Then
fullString = fullString.Remove(0, 1)
End If
'now we have a name, make sure that name is selected
Dim item As ListItem = Me.AdditionalEmailList.Items.FindByValue(listName)
If Not item Is Nothing Then
item.Selected = True
End If
End While
End If
End If
'now to resave the selected values on the list box
Dim entryString As String
'get the selected values from the list box and concatenate them into one string
'this is where I get the problem - selectedindex is 0
If Me.AdditionalEmailList.SelectedIndex <> 0 Then
Dim li As ListItem
entryString = ""
For Each li In Me.AdditionalEmailList.Items
If li.Selected = True Then
entryString += li.Value + ","
End If
Next
'now remove the final comma
Dim finalChar As Integer = entryString.Length
entryString = entryString.Remove(finalChar - 1, 1)
End If
Thanks in advance.