5

I have user control named DateTimeUC which has two textboxes on its markup:

<asp:TextBox ID="dateTextBox" runat="server"></asp:TextBox>
<asp:TextBox ID="timeTextBox" runat="server"></asp:TextBox>

I am dynamically creating this control in another user control:

Controls.Add(GenerateDateTime(parameter));
private DateTimeUC GenerateDateTime(SomeParameter parameter)
{
    DateTimeUC uc = new DateTimeUC();
    uc.ID = parameter.Name;
    return uc;
}

But when I render the page, DateTimeUC renders nothing. I checked it like this:

protected override void Render(HtmlTextWriter writer)
{
    base.Render(writer);

    StringBuilder builder = new StringBuilder();
    StringWriter swriter = new StringWriter(builder);
    HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
    base.Render(hwriter);
    string s = builder.ToString();
}

s is empty and Controls.Count is 0. What am I doing wrong?

womp
  • 115,835
  • 26
  • 236
  • 269
Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138

3 Answers3

9

You must use the LoadControl( "your_user_control_app_relative_path.ascx" ) method instead of "DateTimeUC uc = new DateTimeUC();"

TcKs
  • 25,849
  • 11
  • 66
  • 104
  • Been looking for an answer to this all day. Thanks! – McMuttons Sep 20 '10 at 12:58
  • How can I load a user control that is embedded in a dll? – Zolomon Jun 28 '12 at 07:39
  • @Zolomon: You need the *.ascx file. The *.ascx file contains the asp.net markup which is used for autogenerated class. The autogenerated class inherits from class in assembly (*.dll). – TcKs Jun 28 '12 at 07:53
0

I ran into this problem myself a while back. You need to use the LoadControl() method. Check out this page on it.

ajh1138
  • 566
  • 3
  • 10
0

I think you want to add your control to the page's form & not the form itself.

your code:

Controls.Add( GenerateDateTime(parameter) );

try:

Page.Form.Controls.Add( GenerateDateTime(parameter) );