views:

165

answers:

2

How can i restrict adding controls in Panel in C# window controls? I have to restrict user to add controls in a panel at design time.

A: 

Set AllowDrop to false.

Echostorm
Sorry dude,this will not work. :(
Lalit
Sorry, You might need to add a bit more detail to your problem then brother, from where I sit that should do it.
Echostorm
AllowDrop property defines wether can we drag and drop some data onto the control. It does nothing with allowing or disallowing adding controls into panel. My prob is as simple as stated. I have to restrict user from adding controls on a panel by drag drop as well as by code. Neways thanks.
Lalit
+1  A: 

If you want to limit the types of controls or number of controls one can add to the panel you can make your own subclass of the panel and check the Control type or Control count in an overload of the Controls.Add method.

Edit: Overloading the Controls.Add method was not as easy as I thought, but you can make a new class that extends the Panel class and override the OnControlAdded method to check the type of control that was added. Something like this should work:

class MyPanel : Panel
{

 public MyPanel()
 { }

 protected override void OnControlAdded(ControlEventArgs e)
 {
  base.OnControlAdded(e);

  if (!(e.Control is Label))
  {
   MessageBox.Show("control " + e.Control.Name + " is not a label but a " + e.Control.GetType().ToString());
   Controls.Remove(e.Control);
  }

 }

}
Rune Grimstad
And how can i override Controls.Add Method?
Lalit