Creating Properties and Events for Custom Controls

We can create Properties and events for custom controls for the better re-usability of the control. By adding properties and events, you can extend the value of controls and make them easier and convenient for the developers to work in an integrated development environment. Additionally, validations may also need to be performed on the fields. To achieve these objectives, properties need to be written for every field that needs to vary and validated.

'NewRepeater.cs' shows the code for creating custom control with properties:-

NewRepeater.cs

using System;
using System.Web;
using System.Web.UI;
namespace MyOwnControls
{
    public class TextRepeater :
Control
    {
        public int timesToRepeat;
        public string myText;
        public int TimesToRepeat
        {
           
get
            {
                return timesToRepeat;
            }
           
set
            {
                if (value > 10)
                    throw new ArgumentException("The text should not be repeated more than 10 times");
               
else
                    timesToRepeat = value;
            }
        }
        public string MyText
        {
           
get
            {
                return MyText;
            }
           
set
            {
                if (value.Length > 25)

                    throw new ArgumentException("The text should not be more than 25 characters ");
               
else
                    myText = value;
            }
        }
        protected override void Render(HtmlTextWriter write)
        {
            for (int Count = 1; Count <= TimesToRepeat; Count++)
            {
                writer.write("<h1>" + MyText + "</h1><br>");
            }
        }
    }
}


In the above code the namespace of the control is MyOwnControls. In the next line, a class called TextRepeater is created, which inherits from the Control class. The class control in the namespace System.Web.UI defines the properties, methods and events that are shared by all the ASP.NET server controls. The TimesToRepeat and MyText are properties which sets the text that has to be rendered on the client and sets the number of times the text to be repeated. Also the length of the text is not allowed to be more than 25 characters and it cannot be repeated more than ten times. The for loop of the Render() method uses the TimesToRegister property to set its upper loop limit. The Render() method takes one parameter writer, an HtmlTextWriter object. The HtmlTextWriter object writes the content to be rendered on the client browser. The Write() method of the writer object is used to render the content on the client. The Write() method, which writes a single line of HTML code, is enclosed in a loop.

Ebook Download
View all
Learn
View all