Inherit properties into custom control C#

860 Views Asked by At

I have a custom control that I have created with a bunch standard windows asp controls on it.

Question:

Is it possible to inherit the properties of the parent control into the custom control without re-inventing the wheel?

So for example I have a control with a Button, a TextBox, and a Label.

Normally I can access the properties of that control via Lable1.Text however when these controls are places within a custom control how do I access them without encapsulating all the properties of that control individually.

I was hoping for something like CustomControl1.Lable1.Text or is this not possible

If I use this public Label lbMovieName { get { return this.lbMoveName; } set { lbMovieName = value; } }

I get what I need but can you please tell me why I should not do it?

3

There are 3 best solutions below

7
D Stanley On

The easiest way is to expose the control through a public read-only property:

public Label MyLabel
{
    get { return this.Label1; }
}

However encapsulating just the values you want to expose is definitely a cleaner solution for several reasons:

  1. you can abstract away that actual control type versus being tied to a Label in this case - if you expose the control it will be difficult to swap out the Label with MyNewCoolLabel, for example
  2. You may be exposing more that you want to - the client could change the display properties of the label, etc.
3
Floremin On

The best way and the best practice, I think, is to create properties of your custom control that expose only and exactly what you need. Everything else inside your control should remain private. Something like this:

public string LabelText {
    get { return this.Label1.Text; }
    set { this.Label1.Text = value; }
}

... and so on for the rest of the properties you need exposed. This will give you nice intellsense response in the designer as well.

0
Dwayne F On

If you are trying to avoid creating properties you can make the controls public (this is not sound OO development). As others have already mentioned you'd be much better served exposing the information that you'd want to share via properties.