Can I combine a Type with a variable?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sinnatra
    New Member
    • Jul 2007
    • 1

    Can I combine a Type with a variable?

    Hi,

    I am taking a beginning VB.Net class and I have a project where I need to check the text of 16 buttons. I can easily do this with If Then statements but I am curious if I could do this by running a For Next loop. Here is the code I have tried:

    Code:
    Dim btn As Integer
    Dim x As String
    
            For btn = 1 To 16
                x = btn
                If Button(x).text = "" Then
                    MsgBox("Everything appears correct except you still have blanks in the puzzle.")
                End If
            Next btn
    Unfortunately, I get the following error: 'Button' is a type and cannot be used as an expression.

    Can anyone please help a noob and guide me in the right direction? Thanks!
  • Killer42
    Recognized Expert Expert
    • Oct 2006
    • 8429

    #2
    Hi sinnatra.

    This is one case where M$ appear to have taken a big step backward (though presumably they had their reasons).

    In VB6 (pre-.Net version, about 9-10 years old) you can just define the controls as a control array. So if your control name was called Button1, for instance, you could refer to the elements of the array as Button1(x).

    In VB.Net apparently they have removed this capability. But there are ways to simulate it, or work around the limitation. There is a Controls collection, which I think exists in both VB6 and later versions. You reference the members by name. For example Form1.Controls( "Button1"). The implication of this is that you can get close to the functionality of a control array by dynamically building the name in the string. For example, to access a bunch of buttons called Button1 through Button10, you might do something like this (keeping in mind I only know VB6 syntax)...
    [CODE=vb]
    Dim I As Long
    Dim CtlName As String
    For I = 1 to 10
    CtlName = "Button" & Format(I)
    Debug.Print CtlName ; " : "; Form1.Controls( CtlName).Captio n
    Next
    [/CODE]
    If you search through the discussions which have taken place on this topic at TheScripts, you'll also find that I proposed an alternative method some months back, involving the creation of an array in code to represent the controls on the form. I haven't had a chance yet to flesh it out and write it up in the Articles section (assuming it works out). I'm hoping to do so within the next week or two, but things are pretty busy.

    Ahah! Found it. Just in case you're interested, here is a link to the original discussion during which I proposed the alternative method.

    Comment

    Working...