简体   繁体   中英

I'm writing a control to my aspx file from the aspx.cs file. Why am I getting this error when attempting to use the control?

I have an empty HTML div in my aspx file:

<div id="containingDiv" runat="server">
</div>

My aspx.cs file is writing some HTML to the aspx file like this...

containingDiv.InnerHtml = "<uc:myControl runat='server' id='thisControl'/>";

Later in my aspx.cs file, the control is being acted on... sorry to be vague here but I'm not entirely clear about what it's doing I just know it's being used...

thisControl.somePropertyOrAction....

And I'm getting this error:

The name 'thisControl' does not exist in the current context.

Any ideas why? Many thanks.

您可以按ID在aspx.cs文件中使用和使用它。

I think you need to find the control in your html when you run the "being acted on".

Try something like this:

var control = containingDiv.FindControl("thisControl");
control.somePropertyOrAction = ...

This is how you load user controls dynamically in ASP.NET:

protected void Page_Load(object sender, EventArgs e)
{
    myControl control = LoadControl("~/myControl.ascx") as myControl;
    containingDiv.Controls.Add(control);
}

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