I have a program that adds controls on the fly to an auto-scroll panel. When the panel is scrolled (viewing the bottom of the panel for example) and a control is added, it looks like it is added assuming the top left corner of the panel is still at 0,0 when in fact it may be 0,500. To see what I am talking about, create an empty "Windows Forms Application" project and insert the below code into it.
Friend WithEvents Panel1 As System.Windows.Forms.Panel Friend WithEvents btnAdd As System.Windows.Forms.Button Dim ButtonCount As Integer Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click Dim OnTheFlyButton = New Button OnTheFlyButton.Location = New Point(10, 100) OnTheFlyButton.Name = "Button" & ButtonCount.ToString OnTheFlyButton.Text = "Button " & ButtonCount.ToString Panel1.Controls.Add(OnTheFlyButton) OnTheFlyButton.BringToFront() ButtonCount += 1 End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.Panel1 = New System.Windows.Forms.Panel Me.btnAdd = New System.Windows.Forms.Button Me.SuspendLayout() ' 'Panel1 ' Me.Panel1.AutoScroll = True Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.Panel1.Location = New System.Drawing.Point(0, 57) Me.Panel1.Name = "Panel1" Me.Panel1.Size = New System.Drawing.Size(200, 100) Me.Panel1.TabIndex = 0 ' 'btnAdd ' Me.btnAdd.Location = New System.Drawing.Point(4, 28) Me.btnAdd.Name = "btnAdd" Me.btnAdd.Size = New System.Drawing.Size(75, 23) Me.btnAdd.TabIndex = 5 Me.btnAdd.Text = "Add" Me.btnAdd.UseVisualStyleBackColor = True ' 'Form1 ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(300, 200) Me.Controls.Add(Me.btnAdd) Me.Controls.Add(Me.Panel1) Me.Name = "Form1" Me.Text = "Form1" Me.ResumeLayout(False) End Sub
Now run the app and click the Add button. Scroll the panel down and you will see where it added Button 0. Click the Add button again. You will have to scroll down again to see Button 1. Add several buttons by scrolling down and then clicking the Add button. Now scroll up a little ways (not clear to the top) and click the Add button again. Scroll down a little and you will see where it created the new button over top of the old ones.
Since the location of the new button is forced to be at 10, 100 , it can't be a program bug calculating the new location incorrectly. So, what is causing it to do this and what is the proper way of adding these buttons. Do I have to try to determine how much the screen has been scrolled (i.e. find the actual panel coordinates of the upper left corner) in order to add them in the proper location?