CJLeit Posted July 5, 2006 Posted July 5, 2006 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! Quote
Leaders snarfblam Posted July 5, 2006 Leaders Posted July 5, 2006 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. Quote [sIGPIC]e[/sIGPIC]
Diesel Posted July 5, 2006 Posted July 5, 2006 public new string Controls { get { return base.Controls; } set { ; } } Quote
Leaders snarfblam Posted July 5, 2006 Leaders Posted July 5, 2006 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: public new ControlCollection Controls{ get { throw new Exception("Can't touch this!"); } } A coder can do this: ((UserControl)WhatEverYouAreTryingToProtect).Controls.Clear(); And there is nothing you can do to stop him because that is just the way that a UserControl works. Quote [sIGPIC]e[/sIGPIC]
Diesel Posted July 5, 2006 Posted July 5, 2006 The string was there because it was just an example. Yeh, you can't hide the control collection. Quote
CJLeit Posted July 6, 2006 Author Posted July 6, 2006 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! Quote
Leaders snarfblam Posted July 6, 2006 Leaders Posted July 6, 2006 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. Quote [sIGPIC]e[/sIGPIC]
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.