UserControl Control Collection

CJLeit

Freshman
Joined
Feb 1, 2006
Messages
32
I have a UserControl that consist of several other controls. I want to make sure any changes that are made to the controls are done through my class. The problem is I can go through the Controls Collection of my UserControl and modify them that way. Is there a way to make the Controls Collection of a UserControl read only?

Thanks!
 
Because your control inherits UserControl, it inherits all the behavior and properties of UserControl, whether you like it or not, with the exception of virtual functions and properties, whose behavior can be modified (and which the Controls property isn't). You can hide the controls collection by declaring a property with the same name and same signature and using the "new" modifier, but a coder can always cast your control to a UserControl and access the real, modifiable control collection.
 
What is that? Diesel, you can't return a control collection from a property of type string. Besides, the UserControl.Controls property is already read-only. The problem is that a coder can obtain the ControlCollection and modify that object, regardless of whether or not it is retrieved from a read-only property.

Even if we did this:
C#:
public new ControlCollection Controls{
    get {
        throw new Exception("Can't touch this!");
    }
}
A coder can do this:
C#:
((UserControl)WhatEverYouAreTryingToProtect).Controls.Clear();
And there is nothing you can do to stop him because that is just the way that a UserControl works.
 
The string was there because it was just an example.

Yeh, you can't hide the control collection.
 
I think setting it so accessing the ControlsCollection throws an error will do what I need it too. However I do access the collection in my user control. So now it throws that exception when I try and access the collection in my control. Is there a way to tell if the procedure was called from within my class or from an external class?

Thanks!
 
In your class, call base.Controls (or MyBase.Controls in VB). If you are hiding (shadowing) the base member, a coder can still get at it though, using the method I showed above.
 
Back
Top