0

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

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

我可以使用 Text Visualiser 看到 lbTest.Text 已成功更改,但在母版页上的实际 textBox 中没有任何变化。怎么了?

4

2 回答 2

2
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**
于 2013-02-01T09:14:09.943 回答
2

您必须在 master 中提供一个公共属性作为TextBox. 然后你只需要相应地转换Master页面的属性。

在你的主人:

public TextBox MasterTextBox { 
    get {
        return txtMasterTextBox;
    } 
}

在您的子页面中(假设您的主人的类型是MyMaster):

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

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

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

例如:

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

并在内容页面中:

((MyMaster) this.Master).MasterTextBoxText = childTextBox.Text;
于 2013-02-01T08:58:10.277 回答