1

我正在尝试制作其中有一系列按钮。单击每个按钮,然后在它旁边有一个标签,记录按钮获得的点击次数。

然后我能够从该集合中获得最大的整数(单击按钮的最大次数)。所以我得到了这个数字,我很困惑如何将最高数字与点击次数最多的按钮相关联,以便我可以自动在显示最常用按钮的列表框中添加一个项目。

//////--Code to import the greatest integer of all the collection (clicked more times)---

`Private Sub Button1_Click_2(ByVal sender As System.Object, ByVal e As `enter code here`System.EventArgs) Handles Button1.Click
1.  Dim nums() As Integer = {x1.Text, x2.Text, x3.Text, x4.Text, x5.text}
2.     Dim qry = From n As Integer In nums Order By n Descending
3.        For Each n As Integer In qry
4.            listbox1.Items.Add(n)
5.  Next
6. End Sub`


//////---code to get the single number which was greater than every other in the collection///-

`Private Sub Button2_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
1. Dim nums() As Integer = {x1.Text, x2.Text, x3.Text, x4.Text, x5.text}
2. Dim qry = From n As Integer In nums Order By n Descending
3.        Dim res As Integer = nums.Max.ToString
4.        For Each i As Integer In nums
5.            If i > res Then res = i
6.            Label120.Text = res.ToString
7.        Next
8.        Return
9. End Sub`
4

2 回答 2

1

首先定义一个类来保存对按钮和标签的引用。

Public Class ClickTracker
    Public Property Button As Button 
    Public Property Label as Label
    Public Property ClickCount as Integer

    Public Sub New(button as Button, label as Label)

        Me.Button = button
        Me.Label = label
        Me.ClickCount = 0
        AddHandler Me.Button.Click, AddressOf ButtonClick

    End Sub

    Public Sub ButtonClick (sender As Object, e As EventArgs)
        Me.ClickCount = Me.ClickCount + 1
        Me.Label.Text = Me.ClickCount.ToString()
    End Sub
End Class

如您所见,该类引用您的按钮+标签对,并为按钮单击连接一个事件处理程序。

现在在您的表单中定义一个集合,该集合将包含您要跟踪的所有按钮。

Dim clickTrackers = New List(Of ClickTracker) From {
    {Me.Button1, Me.Label1},
    {Me.Button2, Me.Label2},
    ....ect

这就是你需要做的所有事情。您可以随时查询列表以查看哪些按钮有多少次点击,完全独立于您的其余逻辑。

您将不得不原谅我的 VB,我一直在做 C#,我忘记了很多关于语言的内容,但这应该足够接近了。

于 2013-08-04T01:31:56.113 回答
0

首先要做的是确定按钮(btnABC01、btnABC02、btnABC03 等)和标签(lblABC01、lblABC02、lblABC03)的通用命名模式。并将所有标签设置为初始值 0。

现在为按钮声明一个公共单击事件处理程序,并使用 Form.Load 事件处理程序中的 AddHandler 方法将该处理程序分配给每个按钮

For Each b as Button In Me.Controls.OfType(Of Button)
    If b.Name.Contains("ABC") Then
        AddHandler b.Click, AddressOf Button_Click
    End If
Next

现在在 click 事件处理程序中声明一个临时按钮以等于被单击的按钮(Dim ClickedButton As Button = DirectCast(sender, Button))。对相应的标签执行相同操作并增加其值

Private Sub Button_Click(sender As Object, e As EventArgs)
    Dim ClickedButton As Button = DirectCast(sender, Button)
    Dim LabelToSet As Label = DirectCast(Me.Controls("lblABC" + CilckedButton.Name.Substring(ClickedButton.Name.Length - 2)), Label)
    LabelToSet.Text = (Val(LabelToSet.Text) + 1).ToString
End Sub

然后Me.Controls.OfType(Of Label).Max应该找到数字最高的标签

于 2013-08-03T23:20:31.187 回答