views:

1749

answers:

3

I have to override Add method of "Controls" property of myControl that is extended from a Panel control of windows. For that i extended ControlCollection class into MyControlCollection where i overriden its Add method. Now i declared a Controls property of MyControlCollection type to hide panel's Controls property. When i am accessing this.Controls.Add(control), it refers to overriden Add method. But if i drags and drops a control on myControl the behaviour is of base type's Add method. Can any body suggest the cause and remedy for this problem? Thanks in advance.

A: 

The cause is that the designer is calling Control.Controls rather than accessing your separate collection. To be honest, your solution sounds like it's destined to cause trouble - hiding members usually does.

What are you trying to achieve, exactly? It doesn't look like there's a nice event to hook into in ControlCollection but there may be a different way of tackling the problem.

EDIT: I've just seen that Control has a ControlAdded event - would subscribing to that be enough for you?

Jon Skeet
I have to restrict adding controls in myControl based on some property. ControlAdded fires after adding new control in parent at location 0,0. after which it relocates the control to desired position. If i removes that new control from parent in ControlAdded's EventHandler, exception occurs.
Lalit
+3  A: 

You may instead override the CreateControlCollection function, and return an instance of the class of your choice, which inherits System.Web.UI.ControlCollection. Remove the Controls property from your class, you should not need to override or hide original implementation.

baretta
Ooh, nice - I wasn't aware of that. I think I'd still attempt to not require my own ControlCollection in the first place if possible, but it's nice to know it can be done :)
Jon Skeet
There is no such overridable method for control in windows.
Lalit
sorry, my bad... Guess i read your post a little too fast, and thought you were in an ASP.NET context. However, in Windows Forms, you can do exactly the same by overriding the CreateControlsInstance function.
baretta
A: 

Actually i have to restrict adding controls in my control if some flags are true. I used that ControlAdded event but it added problems only. ControlAdded fires only after adding the that control in parent at location 0, 0. After raising that event it relocates the control according to mouse position at droping time. If i removes that new control from parent in ControlAdded's EventHandler exception occurs.

Lalit