【问题标题】:How to loop through each button to check if they are enabled or not?如何遍历每个按钮以检查它们是否启用?
【发布时间】:2012-06-13 22:45:34
【问题描述】:

我想做一个 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

【问题讨论】:

  • 这是您正在使用的代码,但您只是不理解它,所以您希望对其进行解释,或者是否存在特定错误?所有按钮都添加到 btnCollection 中了吗?

标签: vb.net button loops for-loop each


【解决方案1】:

您可以尝试使用这种方法解决它

  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

【讨论】:

  • 但这是一个私人的子权利,所以我不会在按钮下工作吗?因为我需要它在 num 次后检查所以 afyer btn 被点击了六次,然后检查 wht btns 是否已启用并获取其标签中的值
【解决方案2】:

您似乎在做“一掷千金”的游戏。

您可以创建一个按钮点击计数器(表单级别变量),以便跟踪已经点击了多少按钮。每次单击按钮时计数器都会增加。

创建一个函数来累积标签的值。仅当计数器可被 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多