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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 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 – Ňɏssa Pøngjǣrdenlarp May 03 '15 at 23:45
  • possible duplicate of [Referencing an object using a variable string in Visual Basic 2010](http://stackoverflow.com/questions/3887878/referencing-an-object-using-a-variable-string-in-visual-basic-2010) – Enigmativity May 04 '15 at 00: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." – Aleksa Kojadinovic May 04 '15 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 – Aleksa Kojadinovic May 04 '15 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. – Konrad Rudolph May 04 '15 at 16:07
  • Okay I've decided to go with the dictionary method. It works for buttons but not for variables. I can retrieve the value but not change it. I have a dictionary called varDict(of String, integer), and within I have like 10 integer variables. If I wanted to change the value of one of those how would I do that? varDict("var1") = 5 doesn't work – Aleksa Kojadinovic May 04 '15 at 16:27

2 Answers2

0

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

Community
  • 1
  • 1
Chalumeau
  • 101
  • 10
  • 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. – rheitzman May 04 '15 at 15:49
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
rheitzman
  • 2,247
  • 3
  • 20
  • 36