[英]Accessing child controls that are in a templated user control ASP.NET
以下代码已简化。
用户控件ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BaseFormControl.ascx.cs"
Inherits="SOPR.CustomForms.BaseFormControl" %>
<fieldset class="fset1">
</fieldset>
这是我的用户控件代码隐藏:
public partial class BaseFormControl : System.Web.UI.UserControl
{
[TemplateContainer(typeof(ContentContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate Content { get; set; }
void Page_Init()
{
if (Content != null)
{
ContentContainer cc = new ContentContainer();
Content.InstantiateIn(cc);
contentHolder.Controls.Add(cc);
}
}
我在视图中的用法:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddOperator.aspx.cs"
Inherits="SOPR.Cadastro.AddOperator" MasterPageFile="~/MasterPage.Master" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" ID="maincont" runat="server" EnableViewState="true">
<uc:BaseFormControl ID="BaseFormControl1" runat="server">
<Content>
<asp:TextBox runat="server" CssClass="keytbcss" MaxLength="4" ID="keytb"
NewLine="false" />
</Content>
</uc:BaseFormControl>
我试图访问代码隐藏的“keytb”控件,但它就像它不存在(比如使用不存在的变量)。 有任何想法吗?
提前致谢。
解决方案--------------------------
我找到了一个非常好的解决方案,只需将[TemplateInstance(TemplateInstance.Single)]添加到用户控件的ITemplate属性中,一切都会被看到。 我现在可以使用就像它是一个普通的页面控件。
public partial class BaseFormControl : System.Web.UI.UserControl
{
[TemplateContainer(typeof(ContentContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content { get; set; }
...
解决方案--------------------------
我找到了一个非常好的解决方案,只需将[TemplateInstance(TemplateInstance.Single)]添加到用户控件的ITemplate属性中,一切都会被看到。 我现在可以使用就像它是一个普通的页面控件。
public partial class BaseFormControl : System.Web.UI.UserControl
{
[TemplateContainer(typeof(ContentContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content { get; set; }
...
我会用一种方法来访问用户控件中的内容控件:
public Control FindInnerControl (string id)
{
if (contentHolder.Controls.Count > 0)
{
return contentHolder.Controls [0].FindControl (id); //The first control is your ContentContainer
}
return null;
}
然后在你的页面背后的代码中你可以做
TextBox txtKeytbcss = (TextBox) BaseFormControl1.FindInnerControl ("keytbcss");
当您在模板中编写控件时,您将给它一个内容如何的样本。 想象一下,你在模板中给出一个网格的内容,其中一些id为“SomeTextBox”,当网格中的行数增加时,SomeTextBox不会多次出现。 控件将在运行时动态命名。
但是你还有办法,你必须找到容器控件并在其上应用Control.FindControl()方法。 FindControl()获取您在设计时提供的模板控件ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.