开发者

visual basic 2008 control arrays

I'm looking at controlling properties of an array of buttons in VB 2008 (express). I h开发者_开发技巧ave been looking at the sample code from a whitepaper at MS, and it kind of makes my head spin compared to what was done in VB6! (and yes I'm an amateur, so please forgive the poor coding and what is probably a simple question for the experienced here...)

If I'm reading it correctly, the correct way to do it now is to create a separate class, create constructors, etc. for that class, then instantiate it in the project?

I'm trying to use a relatively simple array like this:

    'Create buttons
    'Dim btn(30) As Button
    'For i As Integer = 0 To 29
    '    btn(i) = New Button()
    '    btn(i).Width = 100
    '    btn(i).Height = 30
    '    btn(i).Text = i + 1

    '    btn(0).Left = 120
    '    btn(0).Top = 100

    '    If i >= 1 And i <= 14 Then
    '        btn(i).Left = 120
    '        btn(i).Top = btn(0).Top + (i * 30)
    '    End If

    '    If i = 15 Then
    '        btn(15).Left = 235
    '        btn(15).Top = 100
    '    End If

    '    If i >= 16 And i <= 29 Then
    '        btn(i).Left = 235
    '        btn(i).Top = btn(0).Top + ((i Mod 15) * 30)
    '    End If
    '    Me.Controls.Add(btn(i))

    'Next

If I put it into the load method, then I can't access it from another button, because I think it's in a private subroutine when this snippet is in the load subroutine? Is there a simple way to just have this code so that the btn(i) array is accessible from other functions in the form?


You need to make the button array a field or a property in the class rather than in the load method.

Easiest way is to just move the Dim btn(30) As Button declaration out of the load method into the class (stick it on the line above the load method) and you're done.

One might argue about coding standards and stuff - but I think that'll get you working (-:

Ok, further to the above and your comment, just enough code to illustrate what I was trying to explain. This code will compile and run - button array accessible from two methods within the form class:

Public Class Form1

    Dim btn(30) As Button

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For i As Integer = 0 To 29
            btn(i) = New Button
        Next
    End Sub

    Private Sub DoSomethingElse()
        For i As Integer = 0 To 29
            btn(i).Text = String.Format("{0}", i + 1)
        Next
    End Sub

End Class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜