【问题标题】:Can't pass div ID to code behind although it has runat=server无法将 div ID 传递给后面的代码,尽管它有 runat=server
【发布时间】:2014-03-25 23:14:43
【问题描述】:

我在 FormView 的 ItemTemplate 中有一个 DIV (id=itemButtons)。虽然它有 runat=server 它的 ID 不能传递给后面的代码。我收到未声明 itemButtons 的错误。有什么帮助吗?

代码隐藏

Sub Page_Load() Handles Me.Load
itemButtons.visible = True
End Sub

ASPX 页面

 <asp:FormView ID="FormView1" runat="server" DataKeyNames="IDrecipe" DataSourceID="SqlDataSource1">
<ItemTemplate>
    <div id="itemButtons" visible="false" runat="server">
            <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
            &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
            &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New" Text="New" />
</div>
</ItemTemplate>
</asp:FormView>

【问题讨论】:

    标签: asp.net code-behind formview


    【解决方案1】:

    无法访问,因为它位于FormiewItemTemplate 中。只有位于页面顶部或更好的控件,NamigContainerPage 才能通过Id 直接访问。

    您需要在NamingContainer 上使用FindControl,这是FormView 需要处于ReadOnly 模式,因为它处于ItemTemplate 中。

    代码的好地方是DataBound - 事件:

    Private Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
        Select Case FormView1.CurrentMode
            Case FormViewMode.ReadOnly
                Dim itemButtons = DirectCast(FormView1.FindControl("itemButtons"), HtmlGenericControl)
                itemButtons.isible = True
        End Select
    End Sub
    

    但是,如果您需要在服务器端访问它,为什么不使用呈现为 div 的Panel

    【讨论】:

    • 只要我在 ItemTemplate 中,脚本就可以正常工作,但如果我更改为其他模式(编辑和插入),它会引发错误。
    • 但是我已经在FormView'DataBound-事件中使用了适当的FormViewMode.ReadOnly 展示了一个示例。这总是有效的。如果您在Edit 等其他模板中也有此div,则需要扩展Select Case 。您可以为控件使用相同的 ID,因为它们位于不同的 NamingContainers 中。
    • 谢谢蒂姆,是的,您的代码运行良好。我已将 Select Case 用于其他表单视图....xxxxx
    猜你喜欢
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 2013-03-19
    • 2014-04-05
    • 2012-08-16
    • 2014-12-23
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多