cherry
cherry

Reputation: 5

Looping through checkboxes in vb.net

<asp:CheckBoxList Visible="false" runat="server" Width="500px"  ID="tblAddlProperty"/>

I have a checkbox list like this, I need to store the checked values (single or Multiple) into a string. Could anyone please help me with this?

Upvotes: 0

Views: 573

Answers (1)

Albert D. Kallal
Albert D. Kallal

Reputation: 48989

Ok, you don't quite mention how you fill out this CheckBox list.

but, say we have a list of Cities, and you need to select a bunch, and then return a string.

So, we could have this markup:

        <div style="float:left">
            <style> .butLabel label {margin-left:15px}  </style>
            <asp:CheckBoxList ID="ChkCity" runat="server" CssClass="butLabel"
                DataValueField="id"
                DataTextField="City" > 
            </asp:CheckBoxList>
        </div>
        <asp:Button ID="cmdDone" runat="server" Text="Confirm Cities" cssclass="btn"/>

Note VERY close: a combobox (dropdown list), a ListBox tend to have TWO values that the list can hold.

The "display" text - nice for the end user.

The "value" text - this can be say a PK id of the database in question. From your question, quite much sounds like you want the text.

So, code to fill out the above list can be say this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        LoadData
    End If
End Sub

Sub LoadData()

    Using conn As New SqlConnection(My.Settings.TEST4)
        Using cmdSQL As New SqlCommand("SELECT ID, City from City ORDER BY City", conn)
            conn.Open()
            ChkCity.DataSource = cmdSQL.ExecuteReader
            ChkCity.DataBind()
        End Using
    End Using

End Sub

and now we have this:

enter image description here

Ok, and for our button code to get a "string" of values selected, we can do this:

Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click

    Dim strCities As String = "" ' our city string result

    For Each MySel As ListItem In ChkCity.Items

        If MySel.Selected Then
            If strCities <> "" Then strCities &= ","

            strCities &= MySel.Text
        End If

    Next

    Debug.Print(strCities)

End Sub

So, say we select the first 4 like this:

enter image description here

Then our output will have this:

Output:

Banff,Calgary,Canmore,Edmonton

Upvotes: 1

Related Questions