Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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!

  • Leaders
Posted
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.
[sIGPIC]e[/sIGPIC]
  • Leaders
Posted

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.

[sIGPIC]e[/sIGPIC]
Posted

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!

  • Leaders
Posted
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.
[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...