【问题标题】:Master Page Control access c#母版页控制访问 c#
【发布时间】:2013-02-01 08:54:12
【问题描述】:

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

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

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

【问题讨论】:

  • 所以你在tbTest.Text 上没有得到NullReferenceException
  • 很奇怪,也许您忘记在某处添加if(!IsPostback) 检查并且您也在回发中对主内容进行数据绑定。你必须展示更多。

标签: c# asp.net controls master-pages


【解决方案1】:
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**

【讨论】:

  • 我不明白这与这个问题有什么关系。 childtxt_TextChanged 已被触发,但主文本框在更改后未更新。您的回答只是显示了如何立即回发,这可能需要也可能不需要,但无助于解决问题。
【解决方案2】:

您必须在您的主服务器中提供一个公共属性作为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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多