Reputation: 566
I am using VB and I have a gridview where you can check on edit or delete button.
'I have a list box where user can select multi items red blue green
take all selected item from listbox and add br tag
Dim t As String = ""
For Each item As ListItem In listbox.Items
If item.Selected Then
t += item.Text + " " + " <br/> "
End If
Next
insert that string 't' in database
Dim insertQuery As String = "INSERT [myTable] ([col1]) VALUES (@col1)"
Dim sqlConn As New SqlConnection(myConnectionString)
sqlConn.Open()
Dim cmd1 = New SqlCommand(insertQuery, sqlConn)
cmd1.Parameters.AddWithValue("@col1", t)
cmd1.ExecuteNonQuery()
Issue: when user click on the edit button than I want auto popluate the ListBox. When I run it than it doesn't automaticlly select the items. If it was a textbox or radio buttons, then it would work fine. It's just not working for listboxes.
' This function is when user check on edit button on gridview
Protected Sub edit_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
listbox.Text = gvrow.Cells(3).Text.Replace(" ", "").Replace(" <br/>", "")
Me.ModalPopupExtender2.Show()
End Sub
Upvotes: 0
Views: 697
Reputation: 1473
You should be using the SetSelected
Method of the ListBox
control.
Try this:
'You probably need to clear anything selected first.
listbox.ClearSelected()
Dim tempString() As String = gvrow.Cells(3).Text.Replace(" ", "").Split("<br/>")
For Each s As String In tempString
listbox.SetSelected(listbox.Items.IndexOf(s.Trim()), True)
Next
Edit:
I added a trim so as to hopefully match up to your list. Since you are adding HTML tags it's possible some empty spaces can prevent it from finding a match in your ListBox. You'll have to tweak this, but I confirmed it does work. This is assuming I understand your question correctly :)
To summarize your issue:
You have a Listbox
containing static items. Listbox.SelectionMode
is set to MultiSimple
or MultiExtend
.
You want to be able to pass a string to the Listbox
representing what should be Selected or highlighted.
Upvotes: 0