Use Page.LoadTemplate and Pass Parameters

≯℡__Kan透↙ 提交于 2020-03-05 03:13:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/60122606/use-page-loadtemplate-and-pass-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!