Making skinned custom controls

A simple sample control

Ok, now let's test out our base class by creating a simple sample control. The control will do nothing more than display some text, using a label control and a repeater control.

using System;
using System.Web.UI.WebControls;
namespace MySite.Controls
{
    public class SampleControl : SkinControl
    {
        // ***********
        //  VARIABLES
        // ***********
        private string skinVirtualPath = "SampleSkin.ascx";
        // *************
        //  CONSTRUCTOR
        // *************
        public SampleControl()
        {
            if (SkinVirtualPath == null)
                SkinVirtualPath = skinVirtualPath;
        }
        // *********
        //  METHODS
        // *********
        protected override void Initialize(System.Web.UI.Control skinControl)
        {
            Label label1 = (Label) skinControl.FindControl("Label1");
            Repeater repeater1 = (Repeater) skinControl.FindControl("Repeater1");
            label1.Text = "A few primes";
            repeater1.DataSource = new string[] { "1", "3", "5", "7", "11" };
            repeater1.DataBind();
        }
    }
}

The first thing we do besides of course declaring the class is to hard-code the default virtual path to the skin file for this specific control. In this case SampleSkin.ascx. Once this is done we add the constructor for this class and inside the constructor we need to check whether a virtual path to a skin file is set, if not we use the default path.

The most important thing comes next, and that is overriding the Initialize method to customize it for the control. In the method we first of all locate all the controls in the skin we want to control – in this case a label control and a repeater control. The retrieval process is done by taking advantage of the FindControl method. For this sample the controls in the skin are named Label1 and Repeater1
After we have found our controls we can customize the controls like we see fit.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The greatest performance improvement of all is when a system goes from not-working to working.” - John Ousterhout