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

本文关键字:抓取 控件 ascx 中的 ASP Net | 更新日期: 2023-09-27 18:05:34

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

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

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

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

public TextBox CustomerName {
    get { return txt_CustomerName; }
}

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

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

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

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

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