如何使用数组在VB中创建可变数量的图片框?

时间:2013-11-16 23:45:59

标签: vb.net cookies

我有以下代码,正如您所看到的,我试图在用户按下按钮时使用它需要的“巧克力片”数量并将它们放在表单上的某个范围内。我没有得到任何错误,但没有巧克力片出现。

Private Sub cookiesButton_Click(sender As Object, e As EventArgs) Handles cookiesButton.Click
        Dim XCoord As Integer
        Dim YCoord As Integer
        Dim arraySize As Integer = Integer.TryParse(cookiesTextBox.Text, arraySize)
        Dim loopCount As Integer = 0
        Dim chipCount(arraySize) As PictureBox
        Do
            loopCount += 1
            If loopCount > arraySize Then Exit Do
            chipCount(loopCount) = New PictureBox
            Controls.Add(chipCount(loopCount))
            Do Until XCoord > 0 And YCoord > 0
                XCoord = (Rnd() * 10)
                YCoord = (Rnd() * 10)
            Loop
            chipCount(loopCount).Image = My.Resources.Chocolae_chip_
            If YCoord < 40 Then YCoord += 40
            If YCoord > 362 Then YCoord -= 40
            If XCoord < 116 Then XCoord += 116
            If XCoord > 408 Then XCoord -= 116
            chipCount(loopCount).Top = YCoord
            chipCount(loopCount).Width = 50
            chipCount(loopCount).Height = 50
            chipCount(loopCount).SizeMode = PictureBoxSizeMode.StretchImage
            chipCount(loopCount).Left = XCoord
            chipCount(loopCount).Visible = True

            ' --------------------------------------------------------

            XCoord = 0
            YCoord = 0
        Loop
    End Sub

2 个答案:

答案 0 :(得分:1)

此行不正确:

Dim arraySize As Integer = Integer.TryParse(cookiesTextBox.Text, arraySize)

Integer.TryParse返回True或False,具体取决于cookiesTextBox.Text是否已成功解析为整数。当您将返回值分配给arraySize时,那些转换为-1或0.您应该写一些类似

的内容
Dim arraySize As Integer
If Not Integer.TryParse(cookiesTextBox.Text, arraySize) Then
    ' TODO: Display an error message.
    Return
End If

答案 1 :(得分:0)

刘先生打败了我的TryParse错误,但有一种更清洁的方法可以做到这一点。我会更接近这个:

if Integer.TryParse(cookiesTextBox.Text, chipCount ) then

    For n as integer = 0 to chipCount 
       Dim pic as New PictureBox  

       With pic
          ' ... set all the properties
          .Image = My.Resources.Chocolae_chip_
          .Top = YCoord           ' etc etc etc
          ' ....
       End With
       Me.Contols.Add(pic)
    Next n
 End If

不需要数组,因为它们将存在于控件集合中。 For / Next循环比Do / Loop好得多,因为你知道要循环多少次。