How do I retrieve a comma-delimited string of values from a text box? [closed]
I have a textbox AND 3 checkboxes; checkbox1, checkbox2, checkbox3
In textbox we have 1,2,3
If I type in textbox1 = 1,2 then
checkbox1 and checkbox2 will be checked and checkbox3 will remain unchecked.....
How to do this in vb.net
Use the String.Split function.
Something like this should work out for you:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
For Each s As String In TextBox1.Text.Split(","c)
Dim i As Integer
If Int32.TryParse(s, i) Then
Dim result As Control = Page.FindControl("checkBox" + i.ToString())
If result IsNot Nothing Then
DirectCast(result, CheckBox).Checked = True
End If
End If
Next
End Sub
If your checkboxes are within a different container instead of the main Page you'll need to call FindControlon that control instead of
Page.FindControl`.
EDIT: it sounds like you're going from checkbox selections to build up the textbox value. Based on your comment it also looks like you have a trailing comma, perhaps because you're appending a comma in a loop. You should provide us with code to better understand what you're doing.
To answer the question in your comment, to sort "3,1," you could use this:
Dim input As String = "3,1,"
Dim split As String() = input.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
Dim result As String = String.Join(",", split.OrderBy(Function(i) i).ToArray())
In reality you might want to order by an Integer type, not by strings, since the sorting order will eventually surprise you for larger numbers.
Off the top of my head
dim v = Split(textbox.text, ",")
for each i in v
select case val(i)
case 1:checkbox1.checked =true
case 2:checkbox2.checked = true
case.....
end select
next
精彩评论