0

i want to add all declared buttons into my form

something like:

dim btn1,btn2,btn3 as new button

for each btn as button in declared.buttons
me.controls.add(btn)
next
6
  • NO! you have to add it manually (one by one). Commented Aug 23, 2012 at 15:06
  • 2
    Why don't you add them to a collection like List(Of Button) first? Then you can loop them and do whatever you want to do with them. Commented Aug 23, 2012 at 15:08
  • And how do you expect to lay them out? 150 buttons all separately declared? I'm gonna take a guess there's going to be a better way to do what you're trying to acoomplish Commented Aug 23, 2012 at 15:09
  • 1
    @none 150 buttons? Then you’re doing it wrong. Are you maybe abusing buttons to create interactive graphics? Buttons aren’t really suitable here. And otherwise 150 buttons will simply kill the user interface. Commented Aug 23, 2012 at 15:09
  • 1
    If you just create them as you have above, and without a list, you'd have to use reflection to get all fields from your form. Commented Aug 23, 2012 at 15:18

2 Answers 2

1

You can add the buttons like this:

For i As Integer = 1 To 150
    Dim btn As New Button()
    btn.Name = "btn" + i.ToString()
    Controls.Add(btn)
Next

Later, you can access the buttons like this:

Dim btn As Button = CType(Controls("btn1"), Button)

However, if you are needing to load that many controls dynamically, you may want to reconsider your design. It smells like a bad idea for most situations.

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

2 Comments

I already know about it, i want to know if i can add all declared buttons into my form in my way. Thanks anyway ;)
Ok. The only way you can do that is with reflection.
0

You can get all your buttons you've declared using something like this:

Dim buttons = From fi In Me.GetType().GetFields(BindingFlags.Instance Or BindingFlags.NonPublic)
   Where fi.FieldType Is GetType(Button)
   Select CType(fi.GetValue(Me), Button)

Off the top of my head.. Still working on it.. but You get the idea?

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.