Search code examples
asp.netvb.netselecteditemcheckboxlistlistitem

ASP.NET, VB: checking which items of a CheckBoxList are selected


I know this is an extremely basic question, but I couldn't find how to do this in VB... I have a CheckBoxList where one of the options includes a textbox to fill in your own value. So I need to have that textbox become enabled when its checkbox (a ListItem in the CheckBoxList) is checked. This is the code behind, I'm not sure what to put in my If statement to test if that certain ListItem is checked.

Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged
    If ___ Then
        txtelect.Enabled = True
    Else
        txtelect.Enabled = False
    End If
End Sub

Solution

  • You can loop through the checkboxes in a CheckBoxList, checking each to see if it is checked. Try something like this:

    For Each li As ListItem In CheckBoxList1.Items
        If li.Value = "ValueOfInterest" Then
            'Ok, this is the CheckBox we care about to determine if the TextBox should be enabled... is the CheckBox checked?
            If li.Selected Then
                'Yes, it is! Enable TextBox
                MyTextBox.Enabled = True
            Else
                'It is not checked, disable TextBox
                MyTextBox.Enabled = False
            End If
        End If
    Next
    

    The above code would be placed in the CheckBoxList's SelectedIndexChanged event handler.