【问题标题】:ASP.NET CheckBox not checked on postback without weird hackASP.NET CheckBox 没有在没有奇怪的黑客攻击的情况下在回发时检查
【发布时间】:2016-12-07 02:29:18
【问题描述】:

我有一个带有复选框列的GridView。单击按钮时,应删除选中复选框的所有行。我不知何故偶然发现了一个奇怪而骇人的解决方案,我不知道它为什么会起作用。我已经搜索过相关的 SO 问题。

相关代码:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
    ' I have no idea why this is needed for the checkboxes to work...
    Dim x = imageGridView.Rows
End Sub


Protected Sub RemoveButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles removeButton.Click

    For Each row As GridViewRow In imageGridView.Rows
        Dim selectCheckBox As CheckBox = DirectCast(row.Cells(0).FindControl("selectCheckBox"), CheckBox)
        If selectCheckBox.Checked Then
            Dim fileName As String = row.Cells(1).Text
            ImageList.Remove(ImageList.FindLast(Function(r) r.FileName = fileName))
        End If
    Next
    imageGridView.DataSource = ImageList
    imageGridView.DataBind()
End Sub

aspx:

<asp:GridView ID="imageGridView" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="selectCheckBox" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

要删除的行需要Dim x = imageGridView.Rows 行。我在Page_Init sub 中尝试了我的RemoveButton_Click 代码后发现了这一点,然后删除代码直到它不再工作。 Dim x = imageGridView 是不够的,在Page_Load 做同样的事情是不行的。

我的复选框永远不会被禁用。

那么,简单地说,为什么我必须在 Page_Init 中引用 imageGridView.Rows 才能使我的代码正常工作?

【问题讨论】:

  • 您是在进行完整的回发,还是使用更新面板?
  • 我有一个UpdatePanel addButton 触发,但网格不包含在面板中。

标签: asp.net vb.net checkbox postback


【解决方案1】:

这是一个有趣的行为。如果我在每次回发时将数据绑定到Page_Load 中的 GridView,我会重现该问题。在这种情况下,复选框会在回发时失去选择状态,但如果我们在 Page_Init 中引用 imageGridView.Rows,则不会,正如您所观察到的那样。

解决方案是将数据绑定在If Not IsPostBack 条件块内:

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        imageGridView.DataSource = ImageList
        imageGridView.DataBind()
    End If
End Sub

但是,在这种情况下,我们不能在 Page_Init 中引用 imageGridView.Rows。这样做会导致复选框失去其选择状态(!?!)。

从 GridView 的源代码(假设this source 是可靠的),我注意到访问Rows 集合会触发对EnsureChildControls 的调用,然后调用CreateChildControls。我无法进入 .NET 代码以查看此时会发生什么。在Page_Init 事件处理程序中调用这些方法可能比life cycle of the GridView 中的预期更早。

顺便说一句,访问HeaderRowFooterRow 属性也会触发对EnsureChildControls 的调用,并且对复选框的选择状态具有相同的效果。

【讨论】:

  • 我以为我必须在每次回发时重新绑定数据,否则它不会结转,但显然不是。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 2014-07-03
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
相关资源
最近更新 更多