1

I am trying to add a user control dynamically to an asp.net web page. user control code:

<%@ Control ClassName="CustomParameterView" %>

<script runat="server">
    public string Value { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }

    private void Input_OnTextChanged(object sender, EventArgs e)
    {
        Value = Input.Text;
    }

</script>
<div class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-2 control-label" id="DisplayName"></label>
        <div class="col-sm-3">
            <asp:TextBox ID="Input" runat="server" CssClass="form-control" OnTextChanged="Input_OnTextChanged" />
        </div>
    </div>
</div>

I have added the register line in the .aspx file:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PerCHW.Valkyrie.Server.WebApplication._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <%@ Reference Control="CustomParameterView.ascx" %>
...

The problem is that this:

  var control = (CustomParameterView) LoadControl("CustomParameterView.ascx");

does not compile.

I also saw people trying ti add the ASP. before the UC name but that does not work as well...

What am I doing wrong?

1
  • VDWWD post makes the point about Placeholders. Also you need to add that user control on Page_Init (each time on post back). Here is a link to a blog post that has an entire sample site to add user controls dynamically. blog.regencysoftware.com/post/2012/11/14/… Commented Oct 5, 2016 at 15:00

1 Answer 1

2

It looks like you are not adding the control to a PlaceHolder.

In the .aspx page add a PlaceHolder:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

And then add the Control to the PlaceHolder in code behind:

var control = (CustomParameterView)LoadControl("~/CustomParameterView.ascx");
PlaceHolder1.Controls.Add(control);

Make sure this code is called every time the page is loaded, so don't put it inside a !IsPostBack check or the Control will be gone after PostBack.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.