简体   繁体   English

从 ASP.Net 中的 ascx 页面获取控件

[英]Grabbing a control from an ascx page in ASP.Net

I have an.ascx user control that is in my search.aspx page.我的 search.aspx 页面中有一个 .ascx 用户控件。 How do I grab a control from the.ascx user control in the search.aspx.cs code behind?如何从 search.aspx.cs 代码后面的.ascx 用户控件中获取控件?

keywordSearch.Value = "value"; 
// the code behind can't see the keywordSearch control

Normally inner controls are not exposed from templated user controls, because they're declared as protected .通常内部控件不会从模板化的用户控件中公开,因为它们被声明为protected You can however expose the control in a public property, like this:但是,您可以在公共属性中公开控件,如下所示:

public TextBox CustomerName {
    get { return txt_CustomerName; }
}

Edit: If you need to set the value of the control then you're better off with a property that exposes the value, not the control:编辑:如果您需要设置控件的值,那么您最好使用公开值的属性,而不是控件:

public string CustomerName {
    get { return txt_CustomerName.Text; }
    set { txt_CustomerName.Text = value; }
}

You might be able to provide a public (or internal) property in your user control's code behind that allows "getting" the control in the user control.您可能能够在用户控件的代码中提供公共(或内部)属性,以允许“获取”用户控件中的控件。 You could then access that property from your page's code behind.然后,您可以从后面的页面代码访问该属性。

Try FindControl method to access a control at container page:尝试 FindControl 方法在容器页面访问控件:

((TextBox)Page.FindControl("keywordSearch")).Value = "value";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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