2

I have a loop where I want to add a button every time the loop iterates...

I have this above my while:

Dim mybut As New Button
Dim btn_number As Integer = 0

I have this within my while:

btn_number += 1
mybut.AutoSize = True
mybut.Name = "delete-btn" & btn_number
mybut.Location = New System.Drawing.Point(77, 112)
mybut.Text = "Delete"
With mybut.Controls
.Add(mybut)
End With

But I get an error message... It's on danish, so I have a little trouble translating it to english, I'm sorry.... But it's something about an object that is referring to itself in a loop...

Hope some of you can spot the issue.... It's possible that I'm writing this all wrong... Thanks.

2
  • If btn_number is locally declared then that could be the problem. Kindly include the loop and where you declare the btn_number variable. Commented Nov 15, 2013 at 10:21
  • Well I've tried to remove my btn_number in all places in the script, but doesn't make any difference, so I don't think that's the problem... Commented Nov 15, 2013 at 10:25

2 Answers 2

1

You cannot add the button to its own controls (as you do with mybut.Controls.Add(mybut)).
You have to add it to some container's controls collection, which might be the form itself (Me.Controls.Add)

mybut = New Button
btn_number += 1
With mybut
    mybut.AutoSize = True
    mybut.Name = "delete-btn" & btn_number
    mybut.Location = New System.Drawing.Point(77, 112 + 
                btn_number * (mybut.height + 5))
    mybut.Text = "Delete"
End With
Me.Controls.Add(mybut)  

You probably also want to change the position for each button - as shown here.

As for your edit:
Put this above the loop: Dim mybut As Button
And this inside the loop: mybut = New Button

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

Comments

0

The problem is that you trying to .Add(mybut) to mybut.Controls.

If you are using this code in a loop, you must also consider change the .Location of every button created.

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.