2009-12-09 4 views
1

웹 사용자 정의 컨트롤을 만들고 aspx 페이지에서 사용했습니다. asp.net에서 제공하는 유효성 검사 컨트롤이 서버 컨트롤에 내장되어 있음을 발견했습니다. 사용자 정의 컨트롤에 이러한 유효성 검사 컨트롤을 첨부 할 수 없습니다.유효성 검사 컨트롤은 asp.net의 웹 사용자 정의 컨트롤에 적용되지 않습니다.

예 : TextBox 컨트롤을 사용하고 있다면 RequiredFieldValidator를 적용 할 수 있습니다. 하지만 사용자 정의 컨트롤에 동일한 RequiredFieldValidator를 적용하려고하면 불가능합니다. "ControlToValidate"속성은 내 사용자 지정 컨트롤의 개체 ID를 표시하지 않습니다.

이 문제를 해결할 수있는 사람이 있습니까?

귀중한 시간을 공유해 주셔서 감사합니다.

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

맞춤 검사기를 사용해야 할 수도 있습니다. –

+0

코드를 올리시겠습니까, aspx 페이지 – Saar

+0

에 사용자 정의 컨트롤 및 RequiredFieldValidator가 코딩되어 있습니다. 코드를 게시 해 주셔서 감사하지만 문제가 무엇인지 보여주기 위해 해당 코드를 모두 게시 할 필요는 없습니다. –

답변

1

당신은 직접 CustomValidator를 사용하거나 사용자 지정 컨트롤에 직접의 RequiredFieldValidator를 삽입해야 하나 -


다음은 .cs 파일에서 코드입니다. 물론 빌트인 유효성 검사기는 귀하의 컨트롤과 함께 작동하지 않습니다 ... 그들은 그것으로 무엇을 해야할지 전혀 모릅니다! 그러나 컨트롤에서 내부적으로 TextBox를 사용하는 경우에는 RequiredFieldValidator를 사용할 수도 있습니다.

세 번째 가능성은 ControlToValidate로 참조 할 수있는 속성으로 내부 TextBox를 노출하는 것입니다. 그러나 처음 두 가지 방법이 바람직합니다.

+0

감사합니다. Bryan! 하지만 내 맞춤 컨트롤의 모든 인스턴스가 필요하지는 않습니다. – IrfanRaza

+0

그럴 경우, Required 또는 비슷한 비슷한 컨트롤에 다른 속성을 추가하기 만하면 기본 제공 유효성 검사기가 활성화됩니다. – Bryan

+0

고마워요 Bryan !!! – IrfanRaza

관련 문제