CheckBoxList中的哪个复选框刚刚选中(或未选中)?

时间:2013-11-22 18:24:27

标签: asp.net vb.net

我在aspx文件中有这个复选框:

        <asp:CheckBoxList ID="CBL_LOC" runat="server" RepeatDirection="Horizontal" 
            AutoPostBack="True" Font-Size="Small" Font-Names="Calibri">
        </asp:CheckBoxList>

根据用户之前的输入,在代码隐藏中添加项目,如下所示:

    L = New ListItem
    L.Text = "ALL"
    L.Value = "ALL"
    L.Selected = True
    CBL_LOC.Items.Add(L)

    conn.ConnectionString = strConnString
    conn.Open()
    cmd = New SqlCommand(Sql, conn)
    dr = cmd.ExecuteReader
    While dr.Read
        L = New ListItem
        L.Text = dr(0)
        L.Value = dr(0)
        CBL_LOC.Items.Add(L)
        L.Selected = True
    End While
    dr.Close()
    cmd.Dispose()
    conn.Close()

现在,当用户选中(或取消选中)“ALL”复选框时,我正在尝试使用以下代码检查/取消选中所有项目:

    Dim CBL As CheckBoxList = sender

    If (CBL.SelectedValue = "ALL") Then
        For Each I As ListItem In CBL_LOC.Items
            I.Selected = CBL.Items(0).Selected
        Next
    End If

当ALL复选框从未选中复选到选中时,此工作正常,SelectedValue为“ALL”。但是当取消选中“ALL”并且用户检查“ALL”时,SelectedValue显示为第一个“已选中”复选框的值,而不是“ALL”框。

我在这里遗漏了什么吗?是否有不同/更好的方法来确定复选框列表中的哪个复选框刚刚选中或未选中?

1 个答案:

答案 0 :(得分:2)

我建议通过创建两个链接按钮来选择all并选择由复选框列表之外的控件管理的任何功能,因为这将删除SelectedValue检查逻辑;像这样:

<asp:LinkButton ID="LinkButtonAll" runat="server" OnClick="LinkButtonAll_Click">
    Select All
</asp:LinkButton>
<asp:LinkButton ID="LinkButtonNone" runat="server" 
                OnClick="LinkButtonNone_Click">
    Select None
</asp:LinkButton>

现在在代码隐藏中,让两个链接按钮执行它们的逻辑,如下所示:

' Check all item
Protected Sub LinkButtonAll_Click(sender As Object, e As EventArgs)
    For Each item As ListItem In CBL_LOC.Items
        item.Selected = True
    Next
End Sub

' Uncheck all items
Protected Sub LinkButtonNone_Click(sender As Object, e As EventArgs)
    For Each item As ListItem In CBL_LOC.Items
        item.Selected = False
    Next
End Sub

  

注意:如果您的网页中没有AutoEventWireup="true",那么您需要将Handles语法附加到两个子程序的末尾。