2012-05-11 77 views
3

在複選框的內部檢查可視化基本表單面板並查找哪些被檢查的語法是什麼?我理解我可以如何使用for循環和if語句,但我對語法檢查每個複選框感到困惑。例如:檢查選中哪個複選框使用循環

Dim i As Integer 
For i = 1 To 10 
    'Here is where my code would go. 
    'I could have ten checkboxes named in sequence (cb1, cb2, etc), 
    'but how could I put i inside the name to test each checkbox? 
Next 

回答

2

我不是很熟悉VB.Net語法,但在psudo代碼:

ForEach CheckBox in ControlContainer 
    DoSomething 
Next 

如果你把所有的CheckBox控件的單個容器中 - 例如一個Panel - 然後上面的代碼會迭代每個控件, a CheckBox

7

您需要循環顯示添加了複選框的控件的Controls集合。每個Control對象都有一個Controls集合。我更喜歡這種情況下的For Each循環,所以我立即得到控件而不必使用Controls索引。如果您的CheckBoxes直接添加到Panel中,最簡單的方法是..

For Each ctrl As var In panel.Controls 
    If TypeOf ctrl Is CheckBox AndAlso DirectCast(ctrl, CheckBox).IsChecked Then 
     'Do Something 
    End If 
Next 
+1

第一行應該是'對於panel.Controls'每個CTRL作爲控制 – Wayne

0

試試這個:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
      If CheckBoxList1.Text = "" Then 
       do/display something 
       Exit Sub 
      Else 
       For Each item As ListItem In CheckBoxList1.Items 
        If item.Selected Then 
         do/display something 
        End If 
       Next 
      End If 
     End Sub