Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 497649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T05:48:06+00:00 2026-05-13T05:48:06+00:00

I have created a web custom control and used within an aspx page. I

  • 0

I have created a web custom control and used within an aspx page. I found the validation controls provided by asp.net are applicable to the built in server controls. I am not able to attach these validation controls with my custom control.

For ex. If i am using TextBox control then the RequiredFieldValidator is applicable to it. but when i try to apply the same RequiredFieldValidator to my custom control it is not possible. The property “ControlToValidate” does not show the object id of my custom control.

Could someone help me to rectify this problem?

Thanks for sharing your valuable time.


Below is the code from .cs file –

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;

[assembly: TagPrefix("DatePicker", "SQ")]
namespace DatePicker
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DatePicker runat=server></{0}:DatePicker>")]
    public class DatePicker : CompositeControl
    {
        //To retrieve value i am using textbox
        private TextBox _TxtDate = new TextBox();
        // Image to select the calender date
        private Image _ImgDate = new Image();
        // Image URL to expose the image URL Property
        private string _ImageUrl;
        // Exposing autopostback property 
        private bool _AutoPostBack;
        // property get the value from datepicker.
        private string _Value;
        //CSS class to design the Image
        private string _ImageCssClass;
        //CSS class to design the TextBox
        private string _TextBoxCssClass;
        //to formate the date
        private string _DateFormat = "%m/%d/%Y";
        //to hold javascript on client side
        static Literal _litJScript=new Literal();
        private bool _includeJS = false;

        /**** properties***/

        #region "[ Properties ]"
        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string ImageUrl
        {
            set
            {
                this._ImageUrl = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string Text
        {
            get
            {
                //String s = (String)ViewState["Text"];
                //return ((s == null) ? string.Empty : s);
                return _Value = _TxtDate.Text;
            }

            set
            {
                ViewState["Text"] = value;
                _TxtDate.Text = value;
                _TxtDate.BackColor = System.Drawing.Color.White;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string Value
        {
            get
            {

                return _Value= _TxtDate.Text;
            }

            set
            {
                _Value = _TxtDate.Text = value;
                ViewState["Text"] = _Value;
                _TxtDate.BackColor = System.Drawing.Color.White;
            }
        }
        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public bool AutoPostBack
        {
            get
            {
                return _AutoPostBack;
            }

            set
            {
                _AutoPostBack = value;
            }
        }
        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string ImageCssClass
        {
            get
            {
                return _ImageCssClass;
            }

            set
            {
                _ImageCssClass = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string TextBoxCssClass
        {
            get
            {
                return _TextBoxCssClass;
            }

            set
            {
                _TextBoxCssClass = value;
            }
        }

        [Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
        public string CommandName
        {
            get
            {
                string s = ViewState["CommandName"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["CommandName"] = value;
            }
        }

        [Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
        public string CommandArgument
        {
            get
            {
                string s = ViewState["CommandArgument"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["CommandArgument"] = value;
            }
        }
        [Bindable(true), Category("Custom"), DefaultValue(""), Localizable(true)]
        public string DateFormat
        {
            get
            {
                return _DateFormat;
            }
            set
            {
                _DateFormat = value;
            }
        }

        [Bindable(true), Category("Behavior"), DefaultValue("True")]
        public bool IncludeClientSideJS
        {
            get { return _includeJS; }
            set {
                _includeJS = value;
            }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("True")]
        public override bool Enabled
        {
            get { return _TxtDate.Enabled; }
            set
            {
                _TxtDate.Enabled = value;
                _ImgDate.Visible = value;
            }
        }
        [Bindable(true), Category("Layout")]
        public override Unit Width
        {
            get
            {
                return base.Width;
            }
            set
            {
                base.Width = value;
                _TxtDate.Width = value;
            }
        }
        #endregion

        protected static readonly object EventCommandObj = new object();

        public event CommandEventHandler Command
        {
            add
            {
                Events.AddHandler(EventCommandObj, value);
            }
            remove
            {
                Events.RemoveHandler(EventCommandObj, value);
            }
        }
        //this will raise the bubble event
        protected virtual void OnCommand(CommandEventArgs commandEventArgs)
        {
            CommandEventHandler eventHandler = (CommandEventHandler)Events[EventCommandObj];
            if (eventHandler != null)
            {
                eventHandler(this, commandEventArgs);
            }
            base.RaiseBubbleEvent(this, commandEventArgs);
        }
        //this will be initialized to  OnTextChanged event on the normal textbox
        private void OnTextChanged(object sender, EventArgs e)
        {
            if (this.AutoPostBack)
            {
                //pass the event arguments to the OnCommand event to bubble up
                CommandEventArgs args = new CommandEventArgs(this.CommandName, this.CommandArgument);
                OnCommand(args);
            }
        }

        protected override void OnInit(EventArgs e)
        {

            base.OnInit(e);
            AddStyleSheet();
            AddJavaScript("DatePicker.Resources.prototype.js");
            AddJavaScript("DatePicker.Resources.calendarview.js");

            // For TextBox
            // setting name for textbox. using t just to concat with this.ID for unqiueName
            _TxtDate.ID = this.ID + "t";
            // setting postback
            _TxtDate.AutoPostBack = this.AutoPostBack;
            // giving the textbox default value for date
            _TxtDate.Text = this.Value;
            //Initializing the TextChanged with our custom event to raise bubble event
            _TxtDate.TextChanged += new System.EventHandler(this.OnTextChanged);
            //Set max length
            _TxtDate.MaxLength = 10;
            //Setting textbox to readonly to make sure user dont play with the textbox
            //_TxtDate.Attributes.Add("readonly", "readonly");
            // adding stylesheet 
            _TxtDate.Attributes.Add("class", this.TextBoxCssClass);
            _TxtDate.Attributes.Add("onkeypress", "maskDate(event)");
            _TxtDate.Attributes.Add("onfocusout","isValidDate(event)");

            // For Image
            // setting alternative name for image
            _ImgDate.AlternateText = "imageURL";
            if (!string.IsNullOrEmpty(_ImageUrl))
                _ImgDate.ImageUrl = _ImageUrl;
            else
            {
                _ImgDate.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "DatePicker.Resources.CalendarIcon.gif");
            }

            //setting name for image
            _ImgDate.ID = this.ID + "i";
            //setting image class for textbox
            _ImgDate.Attributes.Add("class", this.ImageCssClass);

            //Initialize JS with literal
            string s = "<script language=\"javascript\">function maskDate(e){var evt=window.event || e;var srcEle = evt.srcElement?e.srcElement:e.target;";
            s = s + "var myT=document.getElementById(srcEle.id);var KeyID = evt.keyCode;";
            s = s + "if((KeyID>=48 && KeyID<=57) || KeyID==8){if(KeyID==8)return;if(myT.value.length==2){";
            s = s + "myT.value=myT.value+\"/\";}if(myT.value.length==5){myT.value=myT.value+\"/\";}}";
            s = s + "else{window.event.keyCode=0;}}";

            string s1 = "function isValidDate(e){var validDate=true;var evt=window.event || e;var srcEle = evt.srcElement?e.srcElement:e.target;";
            s1 = s1 + "var myT=document.getElementById(srcEle.id);var mm=myT.value.substring(0,2);var dd=myT.value.substring(5,3);var yy=myT.value.substring(6);";
            s1 = s1 + "var originalCss =myT.className; if(mm!=0 && mm>12){myT.value=\"\"; validDate=false;}else{if((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0){if(mm==2 && dd>29){";
            s1 = s1 + "myT.value=\"\"; validDate=false;}}else{if(mm==2 && dd>28){myT.value=\"\"; validDate=false;}else{if(dd!=0 && dd>31){";
            s1 = s1 + "myT.value=\"\"; validDate=false;}else{if((mm==4 || mm==6 || mm==9 || mm==11) && (dd!=0 && dd>30)){myT.value=\"\";  validDate=false;}}}}}";
            s1 = s1 + "if(!validDate){myT.style.backgroundColor='#FD9593';myT.focus;}else { myT.style.backgroundColor='#FFFFFF';}}</script>";


            _litJScript.Text = s+s1;
        }

        /// <summary>
        /// adding child controls to composite control
        /// </summary>
        protected override void CreateChildControls()
        {
            this.Controls.Add(_TxtDate);
            this.Controls.Add(_ImgDate);
            if(_includeJS)
                this.Controls.Add(_litJScript);
            base.CreateChildControls();

        }

        public override void RenderControl(HtmlTextWriter writer)
        {
             //render textbox and image
            _TxtDate.RenderControl(writer);
            _ImgDate.RenderControl(writer);
            if(_includeJS)
                _litJScript.RenderControl(writer);
            RenderContents(writer);

        }

        /// <summary>
        /// Adding the javascript to render the content 
        /// </summary>
        /// <param name="output"></param>
        protected override void RenderContents(HtmlTextWriter output)
        {
            StringBuilder calnder = new StringBuilder();
            //adding javascript first
            if (Enabled)
            {
                calnder.AppendFormat(@"<script type='text/javascript'>
                                     document.observe('dom:loaded', function() {{
                                        Calendar.setup({{
                                        dateField: '{0}',
                                        triggerElement: '{1}',
                                        dateFormat: '{2}'
                                     }})
                                    }});
                              ", _TxtDate.ClientID, _ImgDate.ClientID, _DateFormat);
                calnder.Append("</script>");
            }
            else
            {
                calnder.AppendFormat(@"<script type='text/javascript'>
                                     document.observe('dom:loaded', function() {{
                                        Calendar.setup({{
                                        dateField: '{0}',
                                        triggerElement: '{1}',
                                        dateFormat: '{2}'
                                     }})
                                    }});
                              ", _TxtDate.ClientID, null, _DateFormat);
                calnder.Append("</script>");
            }
            output.Write(calnder.ToString());
        }

        private void AddStyleSheet()
        {
            string includeTemplate = "<link rel='stylesheet' text='text/css' href='{0}' />";
            string includeLocation =
                  Page.ClientScript.GetWebResourceUrl(this.GetType(), "DatePicker.Resources.calendarview.css");
            LiteralControl include = new LiteralControl(String.Format(includeTemplate, includeLocation));
            Page.Header.Controls.Add(include);
        }

        private void AddJavaScript(string javaScriptFile)
        {
            string scriptLocation = Page.ClientScript.GetWebResourceUrl(this.GetType(),javaScriptFile );
            Page.ClientScript.RegisterClientScriptInclude(javaScriptFile, scriptLocation);

        }

    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T05:48:07+00:00Added an answer on May 13, 2026 at 5:48 am

    You should either use a CustomValidator, or insert the RequiredFieldValidator directly into your custom control. Of course the built-in validators don’t work with your control… they have no idea what to do with it! But if your control internally uses a TextBox, then you can also have a RequiredFieldValidator there.

    A third possibility is to expose your internal TextBox with a property, which you can then reference with ControlToValidate. However, the first two methods are preferable.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a asp.net 2.0 web site with numerous asp:DropDownList controls. The DropDownList control
I have implemented a set of ASP.NET web custom controls and added these to
I have created Web-Service in asp.net with c# . Now i want to pass
I have a custom ASP.NET user control that is added to a panel on
I have created Custom .NET controls, and I'd like to know if it's possible,
I have a custom ActiveX control that is used by web pages in IE.
I have created a custom server control, deriving from System.Web.Contols.CheckBoxList to customize how a
I have created a custom web control to act as a button with an
Hopefully an easy one, I have created a Custom Repeater control that extends System.Web.UI.WebControls.Repeater.
I have a my own custom web server control. I created separate CSS file

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.