Reputation: 153
In a master page I have an asp:TextBox with the id "txtMasterTextBox". I want to change this textbox's "Text" property from a child page when another textBox in this page with id "childTextBox" Text is changed. In the childTextBox_TextChanged() i have
TextBox tbTest = (TextBox)this.Master.FindControl("txtMasterTextBox");
tbTest.Text = childTextBox.Text;
I can see with the Text Visualiser that lbTest.Text was successfully changed, but in the actual textBox on the master page nothing changes. What is happening?
Upvotes: 0
Views: 3863
Reputation: 460288
You have to provide a public property in your master as accessor for the TextBox
. Then you just need to cast the Master
property of the page accordingly.
in your master:
public TextBox MasterTextBox {
get {
return txtMasterTextBox;
}
}
in your child-page (assuming that the type of your master is MyMaster
):
((MyMaster) this.Master).MasterTextBox.Text = childTextBox.Text;
However, this is just a cleaner way than your FindControl
approach, so i'm not sure why the TextBox
doesn't show your changed text. Maybe it's a DataBind
issue on postbacks.
An even better way would be not to expose the control in the property but only it's Text
. Then you could change the underlying type easily. Consider that you want to change the type from TextBox
to Label
later. You would have to change all content pages with FindControl
, you would not even get a compiler warning but a runtime exception. With the proeprty approach you have compile time check. If you even change it to a property that just gets/sets the Text
of the underlying control, you could change it without changing one of your content pages at all.
For example:
public String MasterTextBoxText {
get {
return txtMasterTextBox.Text;
}
set {
txtMasterTextBox.Text = value;
}
}
and in the content-page(s):
((MyMaster) this.Master).MasterTextBoxText = childTextBox.Text;
Upvotes: 2
Reputation: 1697
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**
Upvotes: 2