代码保持只会在复选框中添加一个第一个选中的名称,而不会添加其他名称。但是每次点击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
答案 0 :(得分: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