2012-06-10 14 views
-1

我想做一個For Each循環,我可以檢查每個按鈕是啓用還是禁用。如果按鈕被啓用,那麼我必須獲得每個按鈕的標籤中的值。我有26個按鈕,每個按鈕都包含不同的值(現金獎勵)。*重要提示:此代碼需要在按鈕下進行,因此每六次按一次它都會檢查按鈕。如何遍歷每個按鈕以檢查它們是否已啓用?

僞代碼:

btncase1.tag = 5 
Begin while statement to go through each button 
    Check each button to see if it is enabled 
    If button is enabled then obtain values 
Next 

實際的代碼我有,但它沒有任何意義,我說:

Public Class Form1 
Dim button As Button 
Dim totalremcases As Integer 
Dim btncase As New Control 
Dim btncollection As New Microsoft.VisualBasic.Collection() 

Private Sub btncase1_Click() 
For Each button As Button In btncollection 
    If btncase.Enabled Then 
     totalremcases = totalremcases + CInt(btncase.Tag) 
    End If 
Next 
+0

這是你正在使用的代碼,你只是不理解而已你想解釋還是有特定的錯誤?所有按鈕都添加到btnCollection中了嗎? – Kyra

回答

5

,你可以嘗試使用這種方法

Public Sub getallcontrolls(controls As System.Web.UI.ControlCollection) 
    Dim myAL As New ArrayList() 
    For Each ctrl As Control In controls 
     If TypeOf ctrl Is Button Then 
      If ctrl.Enabled = True Then 
       Dim tag As String = ctrl.Tag.ToString() 
       myAL.Add(tag) 
      End If 

     End If 
    Next 
End Sub 
解決呢
+0

但這是一個私人子權利,所以我不會在一個按鈕下工作嗎?因爲我需要它檢查幾次,所以afyer btn被點擊六次,然後檢查啓用了哪些btns並獲得了他們的標籤中的值 – driftking96

+0

您稱之爲函數 –

0

你似乎在做一個「交易或沒有交易」類的遊戲。

您可以創建一個按鈕點擊計數器(表單級別變量),以便您可以跟蹤已經點擊了多少個按鈕。每次點擊一個按鈕時增加計數器。

創建一個函數來累加標籤的值。只有當計數器可以被6整除時(你說你每六次檢查一次按鈕被按下)

Dim counter As Integer 
Dim total As Integer 

Private Function AccumulateTags() As Integer 
    Dim ctl As Control 
    Dim total As Integer 
    For Each ctl In Me.Controls 
     If TypeOf ctl Is Button Then 
      If ctl.Enabled = True Then 
       total += Val(ctl.Tag) 
      End If 
     End If 
    Next 
    Return total 
End Function 

Private Function disable(sender As Object) 
    Dim ctl As Control 
    For Each ctl In Me.Controls 
     If TypeOf ctl Is Button AndAlso sender.Equals(ctl) Then 
      ctl.Enabled = False 
     End If 
    Next 
End Function 

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click, _ 
       Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click 
    counter += 1 
    If counter Mod 6 = 0 Then 'Checks if counter is divisible by 6 
     total = AccumulateTags() 
    End If 

    MsgBox("Total" & total) 'Displays total. You may also display it in a label if you want 
    disable(sender) 
End Sub 
相關問題