无法更改呈现的HTML代码中Panel的可见性

时间:2016-12-25 08:18:38

标签: c# asp.net vb.net webforms

我有一个aspx页面(比如MyPage.aspx),其中一部分具有以下结构 -

<asp:DataList ... >
    <HeaderTemplate>
        ...
    </HeaderTemplate>
    <ItemTemplate>
        <asp:Table ID="table" runat="server">
            <asp:TableRow ... >
                <asp:TableCell ... >
                    <asp:ImageButton ID="btnToggle" OnClick="ToggleVisibility" ... >
                </asp:TableCell>
                ...
            </asp:TableRow>
        </asp:Table>
        <asp:DataGrid ... >
        </asp:DataGrid>
        <asp:Panel ID="panel" runat="server" ...>
            <asp:Button ID="button1" runat="server" ...>
            <asp:Button ID="button2" runat="server" ...>
        </asp:Panel>
    </ItemTemplate>
    <AlternatingItemTemplate>
        ...
    </AlternatingItemTemplate>
</asp:DataList>

我要做的是,只要点击btnToggle,就会切换panel的可见性。我在panel中得到ToggleVisibility(),就像这样 -

Dim panelToggle As Panel = sender.Parent.Parent.Parent.Parent.Controls(5)

在此函数中,我可以更改其Visible属性,但其可见性在呈现的HTML页面上没有变化(通过浏览器检查)。

我无法弄清楚为什么会这样。请帮助。

感谢。

1 个答案:

答案 0 :(得分:1)

OnItemCommand事件添加到处理按钮单击的DataList。您不再需要将OnClick事件添加到按钮本身。

<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
    <ItemTemplate>
        <asp:Button ID="btnToggle" runat="server" Text="Button" />
        <asp:Panel ID="panel" runat="server">
            Panel content.
        </asp:Panel>
    </ItemTemplate>
</asp:DataList>

然后在代码背后

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
    //find the panel in the datalist item object and cast it back to a panel
    Panel panel = e.Item.FindControl("panel") as Panel;

    //you can now access it's properties
    panel.Visible = false;
}

VB

Protected Sub DataList1_ItemCommand(ByVal source As Object, ByVal e As DataListCommandEventArgs)
    'find the panel in the datalist item object and cast it back to a panel
    Dim panel As Panel = CType(e.Item.FindControl("panel"),Panel)

    'you can now access it's properties
    panel.Visible = false
End Sub