1

So say I have 10 buttons on my form named btn1, btn2, btn3, etc. And I want to set each of their text properties to something. So I do something like:

For i = 1 To 10
    //something like:
    ["btn" & i].text = 'blah' //hope you understand what I meant here
Next

Can this also be done with variables? Like I have var1, var2, var3, etc. And if I wanted to control each of them, can I do it in a loop and not one by one?

6
  • 2
    Me.Controls("btn" & i.ToString()).Text is close to what you want. alternatively store the name in a List or the control references themselves. Tun on Option Strict though "btn" & i is nonsense Commented May 3, 2015 at 23:45
  • possible duplicate of Referencing an object using a variable string in Visual Basic 2010 Commented May 4, 2015 at 0:31
  • When I try the Me.Controls("btn" & i.ToString()).Text I get an exception: "Object reference not set to an instance of an object." Commented May 4, 2015 at 11:36
  • EDIT: I've just realized that it's not working even if I hardcore the string: me.controls("btn1").text = "asd" gives the same exception Commented May 4, 2015 at 11:38
  • While this is absolutely possible to achieve, it’s probably the worst possible solution. In your particular example, you should be putting the controls into an array/list instead. Commented May 4, 2015 at 16:07

2 Answers 2

0

To get the controls from a form look at this https://stackoverflow.com/a/3426721 it's c# but easy to understand.

Sign up to request clarification or add additional context in comments.

1 Comment

FYI GetNextControl() method of WinForms iterates over all controls including controls nested in containers. It only returns controls that can be tab stops. Not perfect - doesn't look into SplitContainer(), returns scrollbars, maybe other flaws.
0

Note that the Controls() collection is a property of a Container. A Form is a container. If you have controls in a container on a form e.g. a TabControl the buttons on the TabControl are not in the parent form's Controls but in the TabControl.Controls.

    Dim container As Control = Me
    For i = 1 To 2
        container.Controls("Button" & i).Text = "blah2"
    Next

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.