Overriding "Controls" property of a panel in C#

Overriding "Controls" property of a panel in C#

Old forum URL: forums.lhotka.net/forums/t/5666.aspx


Lalit posted on Friday, October 24, 2008

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.

skagen00 replied on Friday, October 24, 2008

You're not going to get the behavior that you want by hiding it, because the call to drag and drop isn't going to have an instance typed as YourPanel, it'll have an instance typed as the ancestor.

The additional behavior you want, is it complementary to base behavior when controls are added? Are you just trying to do some extra tracking/etc on controls being added?

If so, I'd suggest just looking at this method:

    public class MyPanel : Panel
    {
        protected override void AddedControl(Control control, int index)
        {
            ...

        }
    }

AddedControl is called on the owner of the ControlCollection by ControlCollection when a control is added via Add.

Lalit replied on Thursday, October 30, 2008

Hi,

The fuctionality i require is when i drag n drops a control on MyPanel, based upon some properties of MyPanel i have to allow or disallow adding control on MyPanel. Now windows exposes only ControlAdded event for add control action. I found that this event occurs after adding child control on MyPanel at 0, 0 location and after raising that event it relocates the child control according to the mouse position on MyPanel. If i handle that event and removes the child control from list, it throws exception as it is referring that child after that event to relocate the same.

I have not checked that AddedControl method yet, but soon i will work upon it. If you have some another approach for my problem please tell me. It will be a great help.

 

Thanks

Lalit

Copyright (c) Marimer LLC