0

代码保留只会将第一个选中的名称添加到复选框,不会添加其他复选框,但是每次单击 btn 时都会不断添加复选框列表。不知道为什么会这样。请帮忙

Partial Class ShermanZone
    Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            CheckBox()
        End If
    End Sub
    Protected Sub CheckBox() Handles CheckBoxList1.SelectedIndexChanged
        CheckBoxList1.Items.Add(New ListItem("Jeff"))
        CheckBoxList1.Items.Add(New ListItem("Kristin"))
        CheckBoxList1.Items.Add(New ListItem("Scott"))
        CheckBoxList1.Items.Add(New ListItem("Karri"))
        CheckBoxList1.Items.Add(New ListItem("Amy"))
    End Sub
    Protected Sub btnClick_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClick.Click
        Dim strTextBox As String = String.Empty

        For Each picked As ListItem In CheckBoxList1.Items
            If picked.Selected Then
                If String.IsNullOrWhiteSpace(strTextBox) Then
                    strTextBox = picked.Value
                Else
                    strTextBox += ("," & picked.Value)
                End If
            End If
            Exit For
        Next picked

        txtOutput.Text = strTextBox
    End Sub

End Class
4

1 回答 1

2

删除SelectedIndexChanged事件处理程序。

所以与其:

Protected Sub CheckBox() Handles CheckBoxList1.SelectedIndexChanged
    CheckBoxList1.Items.Add(New ListItem("Jeff"))
    ' ..... '
    CheckBoxList1.Items.Add(New ListItem("Amy"))
End Sub

这个:

Protected Sub CheckBox()
    CheckBoxList1.Items.Add(New ListItem("Jeff"))
    ' ..... '
    CheckBoxList1.Items.Add(New ListItem("Amy"))
End Sub

否则,它也会在回发时触发并将所有项目再次添加到列表中。

除此之外,您可以简化您的按钮单击处理程序,您可以在其中附加所选项目的值:

Protected Sub btnClick_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnClick.Click
    Dim picked = From item In CheckBoxList1.Items.Cast(Of ListItem)()
               Where item.Selected
               Select item.Value

    txtOutput.Text = String.Join(",", picked)
End Sub
于 2012-07-20T19:20:26.580 回答