<p>I have a repeater that is bound to some data.</p>

<p>I bind to the <strong>ItemDataBound</strong> event, and I am attempting to <strong>programmatically</strong> create a <strong>UserControl</strong>:</p>

<p>In a nutshell:</p>

<pre><code>void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    CCTask task = (CCTask)e.Item.DataItem;

    if (task is ExecTask)
    {
        ExecTaskControl foo = new ExecTaskControl();
        e.Item.Controls.Add(foo);
    }
}
</code></pre>

<p>The problem is that while the binding works, the user control is not rendered to the main page.</p>

[{'answer_id': 29080, 'author': 'FlySwat', 'author_id': 1965, 'author_profile': 'https://Stackoverflow.com/users/1965', 'pm_score': 1, 'selected': False, 'text': '<p>Eh, figured out one way to do it:</p>\n\n<pre><code>ExecTaskControl foo = (ExecTaskControl)LoadControl("tasks\\\\ExecTaskControl.ascx");\n</code></pre>\n\n<p>It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.</p>\n'}, {'answer_id': 29258, 'author': 'Craig', 'author_id': 2894, 'author_profile': 'https://Stackoverflow.com/users/2894', 'pm_score': 1, 'selected': False, 'text': '<p>You could consider inverting the problem.  That is add the control to the repeaters definition and the remove it if it is not needed.  Not knowing the details of your app this might be a tremendous waste of time but it might just work out in the end.</p>\n'}, {'answer_id': 29503, 'author': 'JasonS', 'author_id': 1865, 'author_profile': 'https://Stackoverflow.com/users/1865', 'pm_score': 0, 'selected': False, 'text': '<p>I think that @Craig is on the right track depending on the details of the problem you are solving.  Add it to the repeater and remove it or set Visible="false" to hide it where needed.  Viewstate gets tricky with dynamically created controls/user controls, so google that or check <a href="http://www.aspnet4you.com/articles.aspx?articleid=5032" rel="nofollow noreferrer">here</a> if you must add dynamically.  The article referenced also shows an alternative way to load dynamically:</p>\n\n<blockquote>\n  <p>Control ctrl=this.LoadControl(Request.ApplicationPath +"/Controls/" +ControlName);</p>\n</blockquote>\n'}, {'answer_id': 29543, 'author': 'abigblackman', 'author_id': 2279, 'author_profile': 'https://Stackoverflow.com/users/2279', 'pm_score': 0, 'selected': False, 'text': '<p>If you are going to do it from a place where you don\'t have an instance of a page then you need to go one step further (e.g. from a webservice to return html or from a task rendering emails)</p>\n\n<pre><code>var myPage = new System.Web.UI.Page();\nvar myControl = (Controls.MemberRating)myPage.LoadControl("~/Controls/MemberRating.ascx");\n</code></pre>\n\n<p>I found this technique on Scott Guithrie\'s site so I assume it\'s the legit way to do it in .NET</p>\n'}]
['https://Stackoverflow.com/questions/29067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1965/']