简体   繁体   中英

ASP.net User control not recognized

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM