Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web

Inherited web control and new properties

4.67/5 (3 votes)
10 Jan 2011CPOL 9.8K  
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)