2009-12-09 7 views
1

J'ai créé un contrôle personnalisé Web et utilisé dans une page ASPX. J'ai trouvé que les contrôles de validation fournis par asp.net sont applicables aux contrôles serveur intégrés. Je ne suis pas en mesure de joindre ces contrôles de validation avec mon contrôle personnalisé.Les contrôles de validation ne s'appliquent pas aux contrôles Web personnalisés dans asp.net

Par ex. Si j'utilise le contrôle TextBox, alors le RequiredFieldValidator est applicable. mais lorsque j'essaie d'appliquer le même RequiredFieldValidator à mon contrôle personnalisé, ce n'est pas possible. La propriété "ControlToValidate" n'affiche pas l'ID d'objet de mon contrôle personnalisé.

Quelqu'un pourrait m'aider à résoudre ce problème?

Merci de partager votre précieux temps.


est Ci-dessous le code de fichier .cs -

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); 

     } 

    } 
} 
+0

Il semblerait que vous deviez utiliser un validateur personnalisé. –

+0

pouvez-vous s'il vous plaît poster votre code, comment vous êtes codé votre contrôle personnalisé et RequiredFieldValidator dans la page aspx – Saar

+0

Merci pour l'affichage du code, mais vous n'avez probablement pas besoin de publier tout ce code afin de montrer quel est le problème. –

Répondre

1

Vous devez soit utiliser un CustomValidator ou insérez le RequiredFieldValidator directement dans votre contrôle personnalisé. Bien sûr, les validateurs intégrés ne fonctionnent pas avec votre contrôle ... ils n'ont aucune idée de ce qu'il faut faire avec! Mais si votre contrôle utilise en interne un TextBox, vous pouvez également y avoir un RequiredFieldValidator.

Une troisième possibilité consiste à exposer votre TextBox interne avec une propriété, que vous pouvez ensuite référencer avec ControlToValidate. Cependant, les deux premières méthodes sont préférables.

+0

Merci Bryan! Mais toutes les instances de mon contrôle personnalisé ne sont pas requises. – IrfanRaza

+0

Dans ce cas, ajoutez simplement une autre propriété au contrôle appelé Required ou similaire, qui active alors le validateur intégré. – Bryan

+0

Merci Bryan !!! – IrfanRaza

Questions connexes