views:

347

answers:

2

I am trying to create a more detailed item template for the standard CheckBoxList control. It exposes an ITemplate property called TemplateControl but I wasn't able to find a straightforward resource on how to actually use it. Here's the code I have so far:

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    MyBase.OnLoad(e)

    Dim items As New List(Of ListItem)
    items.Add(New ListItem() With {.Text = "A", .Value = "1"})
    items.Add(New ListItem() With {.Text = "B", .Value = "2"})
    items.Add(New ListItem() With {.Text = "C", .Value = "3"})

    Dim lst As New CheckBoxList()
    Dim tpl As ITemplate = LoadTemplate("~/CustomListItem.ascx")
    Dim g As New TemplateControlWrapper()
    tpl.InstantiateIn(g)
    lst.TemplateControl = g
    lst.DataSource = items
    lst.DataBind()

    Form.Controls.Add(lst)

End Sub

Class TemplateControlWrapper
    Inherits UserControl

End Class

It seems to be ignoring the TemplateControl property completely. Any ideas?

+1  A: 

You are missing a couple things... this MSDN page has a pretty straightforward example: http://msdn.microsoft.com/en-us/library/36574bf6.aspx

For starters, you are missing INamingContainer.

Bryan
Not sure what you mean? I am trying to replace the TemplateControl on CheckBoxList with a custom UserControl. http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.loadtemplate.aspx
Kevin
Ah... I misunderstood your question. I thought you were creating a new control that behaves like CheckBoxList, but uses a template.
Bryan
+2  A: 

CheckBoxList's TemplateControl property does not actually allow you to modify the template of the CheckBoxList. This is a property inherited all the way from System.Web.UI.Control, and it means the templated control that the CheckBoxList lives in, or put another way, the .aspx page, .ascx user control, or master page that the control lives on. (If the control is included as part of a composite control, I honestly don't know without experimenting if the TemplateControl property would return null, or keep going up the control chain until it found a Page or UserControl.)

The CheckBoxList control does not offer the kind of template modification you are looking to do. You may need to custom-bind a Repeater or DataList (with a CheckBox control in the ItemTemplate) in order to achieve the functionality you're looking for.

David
Thanks for the direct answer. Is this mentioned anywhere in the MSDN documentation or is is just common knowledge?
Kevin
Not sure, I think I stumbled upon it accidentally one day when trying to traverse up a parent control tree and thinking there had to be a better way. It wouldn't surprise me if the documentation on the issue was less than stellar.
David