BrunoLM
BrunoLM

Reputation: 100381

How to modify all ASP.NET controls to inherit from my special control?

TextBox, Label, Panel, ... all inherits from Control.

Is there a way to inherit from Control and make ASP.NET controls inherit from my new control?

For example, I have a control

public class SpecialControl : Control
{
    public string Something { get; set; }
}

Now I want all controls to inherit from it, so

<asp:TextBox ID="tb" runat="server" Something="hello" />

Would be valid.

Upvotes: 2

Views: 605

Answers (3)

coder net
coder net

Reputation: 3475

One thing you can do is to create an extension method as below.

<asp:TextBox id="tst" runat="server" Something="TestValue"></asp:TextBox> 

 public static string GetSomething(this WebControl value)
{
   return value.Attributes["Something"].ToString();
}

I only tested this for a TextBox control. May not be the ideal solution as it is not strongly typed but will work.

Upvotes: 2

James Johnson
James Johnson

Reputation: 46067

As Oded mentioned, you can't modify the inheritance chain of packaged controls.

What you can do is create wrappers for the packaged controls, and implement custom properties and methods in the wrappers. Here's a simple example of how to extend the TextBox:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomTextBox runat=server></{0}:CustomTextBox>")]
public class CustomTextBox: System.Web.UI.WebControls.TextBox
{
    [Bindable(true)]
    [DefaultValue("")]
    public string Something
    {
        get
        {
            string something = (string)ViewState["Something"];
            return (something == null) ? String.Empty : something ;
        }
        set
        {
            ViewState["Something"] = value;
        }
    }

    protected override void RenderContents(HtmlTextWriter output)
    {
        output.Write(Text);
    }
}

Upvotes: 0

Oded
Oded

Reputation: 499302

You can't change the inheritance chain of the controls that are part of the BCL.

Upvotes: 5

Related Questions