RE: Adding a control programmingly

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Bruce Wilson [MCSD] (anonymous_at_discussions.microsoft.com)
Date: 04/01/04


Date: Thu, 1 Apr 2004 06:56:16 -0800

William,
What you want to do is very easily when you utilize the built-in structures of the System.Windows.Forms objects.
In your code segment, you added a control to the form. When you add a control to an object with a ControlCollection structure, it assigns the parent reference of the control to the object, in your case, the form.

To be even more direct, let me point out the ControlsCollection is not the parent of the control you added to the form. It is just a structure to hold references to the controls

You can use the form.Controls(intControlIndex) to access your control. For example:

        Dim aControl As New Button()
        Dim intControlIndex As Integer
        Me.Controls.Add(aControl)
        intControlIndex = Me.Controls.Count - 1
        Me.Controls(intControlIndex).BackColor = System.Drawing.Color.Purple