Click here to Skip to main content
15,886,199 members
Articles / Web Development
Tip/Trick

Inherited web control and new properties

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
10 Jan 2011CPOL 9.6K   3   1
Inherited web control and new properties

I had to extend the .NET Button control, because I needed to extend it with an extra property 'Tag'. I thought "Must be simple", and wrote the code for the new control:


public class MyButton : Button {
     public string Tag { get; set; }
}

If you put the control on a page like this:


<myCtrls:MyButton  runat="server" Tag="let's test tag"  önCLick="Btn_OnClick"/>

Then you'll get your Tag in the Btn_OnClick server event.


PROBLEM


But if you want to place your inherited control into, say, ListView and assign the Tag to some data from a datasource like

<myCtrls:MyButton  runat="server" Tag="<%# Container.DataItemIndex %>"  önCLick="Btn_OnClick" />

Then you will get null in your server Btn_OnClick event method. I don't know exactly why I get null, because if you pass a constant string value, for example, Tag="777", you will get your "777" on the server side.


SOLUTION


You need to modify your auto property in your inherited control in order to get and set your property through the viewstate:


public virtual string Tag
{
           get
           {
                string s = (string)ViewState["Tag"];
                return s ?? String.Empty;
            }
            set
            {
                ViewState["Tag"] = value;
            }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 Good to know! 5 Pin
Manfred Rudolf Bihy11-Jan-11 10:09
professionalManfred Rudolf Bihy11-Jan-11 10:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.