用于循环功能

时间:2013-11-10 10:56:59

标签: vb.net function for-loop

我尝试绘制64个按钮(8行和8列)来制作游戏,但由于某种原因我的代码不起作用。我希望有人可以帮助我。

Public Class Form1
Dim AMOUNTOF_COLUMNS As Integer = 8
Dim AMOUNTOF_ROWS As Integer = 8
Public Function setNew(row As Integer, column As Integer) As Button

    Dim newButton As New Button()
    newButton.Width = 40
    Me.Controls.Add(newButton)
    newButton.Left = 0
    newButton.Top = 0
    newButton.Height = newButton.Width
    newButton.Text = ""
    newButton.Tag = (column + (row * AMOUNTOF_COLUMNS))
    AddHandler newButton.MouseDown, AddressOf Klik
    Return newButton
End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For value1 As Integer = 0 To AMOUNTOF_ROWS Step 1
        For value2 As Integer = 0 To AMOUNTOF_COLUMNS Step 1
            Me.setNew(value1, value2)
        Next
    Next
End Sub

如果我执行此代码,它只会给我一个按钮。

2 个答案:

答案 0 :(得分:2)

你正在绘制64个按钮,但它们都是彼此重叠的。您需要正确地抵消它们。特别是这些线应该被修改,以便每个按钮都能获得正确的位置。

newButton.Left = 0
newButton.Top = 0

编辑:

newButton.Tag = "Column x - row y"

Public Sub Klik(sender as Object, e As EventArgs)
    Dim b as Button = sender
    Dim value as String = b.Tag
    If value = "Column 1 - row 1" Then
         ' Do action for col 1 row 1
    Else If value = "Column 2 row 1" Then
         ' Do action for col 2 row 1
    Else If ...
    Else If ...
    End If
End Sub

答案 1 :(得分:1)

您需要修改方法以将按钮彼此相邻地绘制,并相应地设置其LeftTop属性:

Public Function setNew(row As Integer, column As Integer) As Button

    Dim newButton As New Button()
    newButton.Width = 40
    newButton.Height = newButton.Width
    Me.Controls.Add(newButton)
    newButton.Left = column * newButton.Width ' you may need some offset here too
    newButton.Top = row * newButton.Height ' you may need some offset here too
    newButton.Text = ""
    newButton.Tag = (column + (row * AMOUNTOF_COLUMNS))
    AddHandler newButton.MouseDown, AddressOf Klik
    Return newButton
End Function

此外,您需要在当前创建9行和列时减少一列和一行

For value1 As Integer = 0 To AMOUNTOF_ROWS - 1 Step 1
    For value2 As Integer = 0 To AMOUNTOF_COLUMNS -1 Step 1
        Me.setNew(value1, value2)
    Next
Next