Reputation: 5536
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?
Upvotes: 1
Views: 836
Reputation: 35514
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.
Upvotes: 2