母版页控件访问 c#

本文关键字:访问 控件 母版页 | 更新日期: 2023-09-27 17:57:02

在母版页中,我有一个 asp:TextBox,ID 为"txtMasterTextBox"。当此页面中另一个 ID 为"childTextBox"的文本文本框发生更改时,我想从子页面更改此文本框的"文本"属性。在childTextBox_TextChanged()中,我有

TextBox tbTest = (TextBox)this.Master.FindControl("txtMasterTextBox");
tbTest.Text = childTextBox.Text;

我可以通过文本可视化器看到 lbTest.Text 已成功更改,但在母版页上的实际文本框中没有任何变化。发生了什么事情?

母版页控件访问 c#

you have to do this
In master page.
    Master:  <asp:TextBox ID="txtMasterTextBox" runat="server"></asp:TextBox>
In Child Page.
 child:  <asp:TextBox ID="childtxt" runat="server" ontextchanged="childtxt_TextChanged" **AutoPostBack="true"**></asp:TextBox>
than in Textchange event of child textbox 
 protected void childtxt_TextChanged(object sender, EventArgs e)
        {
            TextBox tbTest = (TextBox)this.Master.FindControl("txtMasterTextBox");
            tbTest.Text = childtxt.Text;
        }
**so basiclly u have to put one attribute "AutoPostback" to True**
您必须

在主节点中提供一个公共属性作为TextBox的访问器。然后,您只需要相应地强制转换页面的 Master 属性。

在您的主中:

public TextBox MasterTextBox { 
    get {
        return txtMasterTextBox;
    } 
}

在您的子页面中(假设您的主控形状的类型为 MyMaster):

((MyMaster) this.Master).MasterTextBox.Text = childTextBox.Text;

但是,这只是一种比您的FindControl方法更干净的方式,所以我不确定为什么TextBox不显示您更改的文本。也许这是回发的一个DataBind问题。

更好的方法是不公开属性中的控件,而只公开它Text。然后,您可以轻松更改基础类型。请考虑稍后将类型从TextBox更改为Label。您必须使用 FindControl 更改所有内容页面,您甚至不会收到编译器警告,而是运行时异常。使用proeprty方法,您可以进行编译时检查。如果甚至将其更改为仅获取/设置基础控件Text的属性,则可以在不更改任何内容页的情况下更改它。

例如:

public String MasterTextBoxText { 
    get {
        return txtMasterTextBox.Text;
    }
    set {
        txtMasterTextBox.Text = value;
    }
}

在内容页面中:

((MyMaster) this.Master).MasterTextBoxText = childTextBox.Text;