2012-07-20 45 views
0

代碼保留只會將一個第一個選中的名稱添加到複選框,並且不會添加其他選項,但每次單擊btn時它都會添加checkboxlist。不知道爲什麼會這樣。請幫助Checkboxlist以編程方式添加,存在問題

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 

回答

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 
+0

感謝上的幫助。工作完美,仍然是這個新手。 – Newbie2012 2012-07-23 12:09:49

相關問題