如何在ASPX页面中引用DOM中的父元素?

时间:2013-09-04 10:05:19

标签: html asp.net dom

这是我的网页摘要:

...
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
  <table>
    <tr>
      <td>
        <asp:TextBox MaxLength="255" ID="myTextBox" runat="server"></asp:TextBox>
      </td>
    </tr>
  </table>
</asp:Content>
...

这是页面代码隐藏的部分:

...
Control parent = this.myTextBox.Parent; //this is acutally asp:Content control
string parentID = parent.ID; //this is PlaceHolderMain
...

我需要的是引用<td>元素(因为我想更改它的Visibility属性)。我怎样才能做到这一点?我在哪里走得这么可怕? :)

4 个答案:

答案 0 :(得分:1)

td需要在服务器端运行才能被访问并归类为父元素。

<td id="td" runat="server">
   <asp:TextBox MaxLength="255" ID="myTextBox" runat="server"></asp:TextBox>
</td>

答案 1 :(得分:1)

后面的ASPX代码真的只知道ASP控件(即标签中带有asp:前缀的那些),td只是普通的旧HTML。为了使后面的代码与它交互,你需要在标签上添加一个runat =“server”

答案 2 :(得分:0)

这里的表是一个html表而不是ASP.NET服务器控件。所以你无法在后面的代码中访问它。

以下情况使用:

<asp:Table ID="Table1" runat="server">
            <asp:TableRow ID="TableRow1" runat="server" ForeColor="Teal">
                <asp:TableCell>
                    <asp:TextBox MaxLength="255" ID="myTextBox" runat="server"> 
                    </asp:TextBox>
                </asp:TableCell>
            </asp:TableRow>
</asp:Table>

答案 3 :(得分:0)

将属性runat添加到<td>标记,与其他用户建议一样。

<td id="mytd" runat="server">
   <asp:TextBox MaxLength="255" ID="myTextBox" runat="server"></asp:TextBox>
</td>

然后在c#侧(页面后面)

添加此标头文件

using System.Web.UI.HtmlControls;
protected void Button_click(object sender,EventArgs e)
{
  mytd.Attributes.Add("style","visibility:none");
}