【问题标题】:Simple VB, handling many buttons简单的VB,处理许多按钮
【发布时间】:2012-12-10 20:56:42
【问题描述】:

在我的 VB 解决方案中,我有很多按网格排列的按钮。加载程序时,其中一个按钮被随机设置为正确的按钮(您必须单击该按钮才能获胜)。谁能指出我正确的方向?因为必须有比手动编码每个按钮并为每个按钮创建事件处理程序更好的方法。

您不必给我一个工作示例,只需大致了解这是如何完成的。

谢谢。

【问题讨论】:

    标签: vb.net events button event-handling


    【解决方案1】:

    如果您想在网格中排列按钮,请使用 TableLayoutPanel 或将按钮直接添加到表单并计算它们的位置。如果您想在表单调整大小时自动排列按钮,TableLayoutPanel 很有用,否则直接添加按钮对我来说似乎更容易。

    将按钮添加到在表单级别定义的数组中以使其易于访问

    Public Const NColumns As Integer = 5, NRows As Integer = 4
    
    Private buttons As Button(,) = New Button(NColumns - 1, NRows - 1) {}
    

    您可以在循环中轻松添加按钮

    For ix As Integer = 0 To NColumns - 1
        For iy As Integer = 0 To NRows - 1
            Dim btn = New Button()
            btn.Text = String.Format("{0:d2}{1:d2}", ix, iy)
            btn.Location = New Point(leftMargin + ix * xDistance,
                                     topMargin + iy * yDistance)
            btn.Size = New Size(buttonWidth, buttonHeight)
            AddHandler btn.Click, Addressof Button_Clicked
            buttons(ix, iy) = btn
            Controls.Add(btn)   
        Next
    Next
    

    您可以使用随机生成器确定获胜按钮。将其定义为表单成员,而不是局部变量。

    Private randomGenrator As System.Random = New System.Random()
    

    确定坐标

    Dim xWins = randomGenrator.Next(NColumns) 'Returns a number between 0 and NColumns-1
    Dim yWins = randomGenrator.Next(NRows)
    

    点击处理程序如下所示

    Private Sub Button Button_Clicked(sender As Object, e As EventArgs)
        If sender = buttons(xWins, yWins) Then
           'You win
        Else
           'You loose
        End
    End Sub
    

    【讨论】:

      【解决方案2】:

      首先,您说您想要一个按钮网格,因此您必须在表单中有一个FlowLayoutPanel 控件,以便让您想要添加的按钮自动排列。 其次,您必须使用 for 循环,r 任何类型的外观,以便将要添加的按钮添加到先前添加的“FlowLayoutPanel”。 课堂答案 将 strAnswerText 调暗为字符串 将 AnswerFlag 暗淡为布尔值 结束类

      Sub LoadForm(byval a_Answers as Answer())        
          Dim i as Integer = 0
          Dim b as Button 
          For(i=0;i<NUM_OF_BUTTONS;i++)
             b = New Button()
             b.Text = "Choice -" & i & "- " & a_Answers(i).strAnswerText 
             b.Tag = a_Answers(i).AnswerFlag
      
             'Supposing that the FlowLayoutPanel control name is fl
             AddHandler b.Click, Addressof Clicked
             fl.controls.Add(b)   
          End For 
      End Sub
      
      Sub Button Clicked(sender as object, e as EventArgs)
          if sender.Tag = True
             'True answer
          else
             'Wrong answer
          end if
      
      End Sub
      

      【讨论】:

      • 不是所有按钮都以这种方式获得“True”标签吗?
      • 是的,您是对的,您必须解决这个问题,例如,您必须给出正确的答案编号作为参数。比如'LoadForm(byval rightanswer as integer)'等等......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 2011-12-02
      • 2020-01-29
      相关资源
      最近更新 更多