How to reference a control which was added programmingly

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi, everyone

After adding a control into a container like form using form.controls.add(myControl), how could I reference it
For example
dim aControl as new butto
me.controls.add(aControl

then I want set backcolor of this button, how

Thanks

william
 
\\\
Dim aControl As New Button

Me.Controls.Add(aControl)

aControl.BackColor = Color.Blue
///

HTH,
Gary

william said:
Hi, everyone,

After adding a control into a container like form using
form.controls.add(myControl), how could I reference it?
 
Hi William,

You can use the same button object till it is within scope. For example,

Dim aControl As New Button
Me.Controls.Add(aControl)

aControl.BackColor = Color.AliceBlue

HTH.
 
william said:
Hi,
The problem is I did it in a function, so the object(control) is out of the scope.
Here is the case:
In my form load event, I call a function to load all controls
programmingly, then in other function, I want to use these controls.
For example,
private sub Form_Load(...)
...
LoadControl
end sub
private sub LoadControl
dim aButton as new button
aButton.name="MyButton"
aButton.text="OK"
'add other properties here
me.Controls.Add(aButton)
...
end sub
private sub MyFunction
...
'todo: need set Backcolor=blue to the button with name of "MyButton"

end sub

How can I get the proper button handler?

thanks

william

The simplest approach is to declare your control variables at the form
scope, not the LoadControl scope. You can then access the variables from any
method in the form class.

Your only other approach is to loop through the controls in the form's
controls collection, looking for the control that matches the criteria you
want to match, then setting the BackColor of that control. This is a very
bad option, though, since you would be looping through every time you wanted
to change a property of a control. Better to just declare the variables at
the form's scope.
 
Back
Top