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

时间:2011-08-15 20:20:41

标签: c# asp.net webforms

我的search.aspx页面中有一个.ascx用户控件。如何从search.aspx.cs代码中的.ascx用户控件中获取控件?

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

3 个答案:

答案 0 :(得分:3)

通常,内部控件不会从模板化用户控件中公开,因为它们被声明为protected。但是,您可以在公共属性中公开控件,如下所示:

public TextBox CustomerName {
    get { return txt_CustomerName; }
}

编辑:如果您需要设置控件的值,那么您最好使用一个公开值的属性,而不是控件:

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

答案 1 :(得分:3)

您可以在用户控件的代码后面提供公共(或内部)属性,以允许在用户控件中“获取”控件。然后,您可以从页面代码后面访问该属性。

答案 2 :(得分:1)

尝试使用FindControl方法访问容器页面上的控件:

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