I need to load a template to an ASP.NET ListView
depending on the type of an object. However, I need to pass parameters to that ItemTemplate
before loading it in. The item template that gets loaded into the list view is a .ascx
user control.
ITemplate template = Page.LoadTemplate("~/Controls/Questions/TrueFalse.ascx");
listView.ItemTemplate = template;
I've tried casting template
as UserControl
or as TrueFalse
(the type of the user control that loads), but both cast to a null.
I need to pass an object with information for the control to display. For example, in this case, the question is a True/False question, so the template will be passed a Question
object that contains the question text plus whether the answer is true or false. There will be other question types, such as Multiple Choice, Short Answer, etc. Each of these needs to get displayed with a different template. How do I pass information to that ItemTemplate
in the ListView
?
I've been using this solution to change templates according to the data's type. I can display different templates according to the data's type; I just don't know how to load the template as a list view item while passing data to it.
Through this blog post, I discovered that the secret is actually in retrieving the bound item, which in the case of a list view, is ListViewDataItem
.
This line of code, in the user control, will retrieve the data bound to the ItemTemplate
and add it to the page (which, in my case, is the Question
object I needed to access):
((Question)(DataBinder.GetDataItem((ListViewDataItem)Container))).WhateverProperty
This front-end code gets surrounded in <%# ... %>
tags, of course.