我正在尝试从用户控件(ascx)中查找aspx页面上的标签。显然,Page.FindControl("lablel1")不起作用。我需要在某个地方添加ClientID吗?谢谢。
我认为你应该停下来,仔细考虑你的设计。你的控件不应该需要了解包含它们的页面 - 你需要从另一个控件中查找页面上的控件这一事实告诉我你应该重新思考这个问题。
根据我所知道的架构,最好的建议是你应该将要查找的控件的引用传递给你的用户控件。这样,你的控件就不必了解自身外部的事物。
FindControl()
时,需要遍历控件树来查找你的Me.Owner.FindControl("controlName")
或者...
Me.Owner.Parent.FindControl("controlName")
或者...
Me.Owner.Parent.Parent.FindControl("controlName")
Protected Function FindControlByID(ByRef childControl As Control, ByVal ID As String) As Control
Dim ctrl As Control = childControl.FindControl(ID)
If Not ctrl Is Nothing Then
Return ctrl
Else
If Not childControl.Parent Is Nothing Then
Return FindControlByID(childControl.Parent, ID)
Else
Return Nothing
End If
End If
End Function
Dim lbl As Label = FindControlByID(Me.Owner, "label1")
public interface IStatusDisplayer
{
Label StatusLabel { get; }
}
在显示错误/状态标签的任何页面上实现接口。如果您的用户控件需要访问该标签,则可以执行以下操作:
var statusDisplayer = this.Page as IStatusDisplayer;
if (statusDisplayer != null)
{
statusDisplayer.StatusLabel.Text = "Hello World!";
}
Control ct = WebUserControl11.FindControl("DropDownList1");
DropDownList dt = (DropDownList)ct;
TextBox1.Text = dt.SelectedValue.ToString();
从用户控件内部
Me.NamingContainer.FindControl("label1")
访问意味着从.aspx文件中启用/禁用.ascx中的控件,请尝试此代码,它也是解决方案。
protected void Page_Load(object sender, EventArgs e)
{
Control ct = PEM.FindControl("btnInsert");
Button btn = (Button)ct;
btn.Enabled = false;
}
这很简单,首先您需要访问主页面ContentPlaceHolder:
Dim ContentPlaceHolder1 As ContentPlaceHolder = TryCast(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
然后,使用ContentPlaceHolder,你现在可以找到aspx页面上控件的ID:
TryCast(ContentPlaceHolder1.FindControl("LiteralOnParentASPXPage"), Literal).Text = "some text"
这是一种蛮力方法,但当控件深度嵌套在控件层次结构中时,它是有效的:
private Control GetTextEditor(ControlCollection controls)
{
foreach (Control ctrl in controls)
{
if (ctrl.ID != null && ctrl.ID == "teMessage")
return ctrl;
if (ctrl.Controls.Count > 0)
{
Control inner = GetTextEditor(ctrl.Controls);
if (inner != null)
return inner;
}
}
return null;
}