From time to time we need to do something that the .Net framework doesn't immediately expose to us (without some finagling). In this instance, I wanted to override the attributes that the labels generated by the CheckBoxList webcontrol. However, I only wanted to modify this one instance of it.
In doing so, I needed to hook into the creation of the item collection of the CheckBoxList control, but I do not know of an event that we can use to do so. So, I instead ran a loop through the controls collection to find the instances of the CheckBoxList control and make the changes I wanted.
Here is an example:
Private Sub ReWriteCheckboxLabels()
Dim ctl As System.Web.UI.Control
Dim ctlCheck As WebControls.CheckBoxList
' loop through all of the controls in the UpdatePanel
' controls collection
For Each ctl In Me.UpdatePanel1.Controls(0).Controls
' make sure that the current control is the right kind
If ctl.GetType.ToString =
_"System.Web.UI.WebControls.CheckBoxList" Then
' yippee! it's a checkbox list - change the type
ctlCheck = CType(ctl, WebControls.CheckBoxList)
' only do this if there are items to change
Select Case ctlCheck.Items.Count
Case Is > 0
' force the label text to inherit the
' correct class
Dim item As ListItem
' loop through the items in the current
' checkbox list
For Each item In ctlCheck.Items
' wrap the text within the label
' to override it's CSS class
item.Text = "<span class=""" & _
"YOURCSSCLASSNAME"">" & _
item.Text & "</span>"
Next
Case Else
'do nothing
End Select
End If
Next
End Sub
In the previous example, I have at least one CheckBoxList control nexted within a MS AJAX UpdatePanel. In order to get to the collection of controls, I need to first reference the controls using the
Controls collection of the first Controls instance in the UpdatePanel.
If you are not nesting your controls a similar way, you can simply modify the first FOR EACH loop to be something more like this:
For Each ctl In Me.Controls
This would loop through all of the controls in the current page or user control.