2009-11-17 162 views
0
public sealed class IntegerBox : TextBox 
{ 
    #region constants 

    private const string RangeConstraintValidatorID = "rangeConstraintValidator"; 

    #endregion 

    #region child controls 

    private readonly CustomValidator _rangeConstraintValidator = new CustomValidator 
    { 
     EnableClientScript = false, 
     Enabled = true, 
     ErrorMessage = "ErrorMessageForRangeConstraintFailed", 
     Display = ValidatorDisplay.None, 
     SetFocusOnError = true, 
     ValidateEmptyText = true 
    }; 

    #endregion 

    #region life cycle 

    protected override void CreateChildControls() 
    { 
     this.Controls.Clear(); 

     this._rangeConstraintValidator.ID = this.ClientID + this.ClientIDSeparator + RangeConstraintValidatorID; 
     this._rangeConstraintValidator.ServerValidate += this.ValidateRangeConstraint; 

     this.Controls.Add(this._rangeConstraintValidator); 

     base.CreateChildControls(); 
    } 

    #endregion 

    /// <summary> 
    /// Gets or sets the number. 
    /// </summary> 
    /// <value>The number.</value> 
    public int? Number 
    { 
     get 
     { 
      /* MAGIC */ 
     } 
     set 
     { 
      /* MAGIC */ 
     } 
    } 

    public override string ValidationGroup 
    { 
     get 
     { 
      this.EnsureChildControls(); 
      return base.ValidationGroup; 
     } 
     set 
     { 
      this.EnsureChildControls(); 
      base.ValidationGroup = value; 
      this._rangeConstraintValidator.ValidationGroup = value; 
     } 
    } 

    public int? MaximumValue { get; set; } 
    public int? MinimumValue { get; set; } 
    public string ErrorMessageForRangeConstraintFailed 
    { 
     get 
     { 
      this.EnsureChildControls(); 
      return this._rangeConstraintValidator.ErrorMessage; 
     } 
     set 
     { 
      this.EnsureChildControls(); 
      this._rangeConstraintValidator.ErrorMessage = value; 
     } 
    } 

    public void ValidateRangeConstraint(object source, ServerValidateEventArgs args) 
    { 
     /* MAGIC */ 
    } 

    #endregion 
} 

誰能告訴我,這是爲什麼不工作?
筆記:爲什麼這個CustomValidator不會觸發?

  • 我已經試圖實例化的rangeConstraint驗證器內部的CreateChildControls =沒有效果!
  • 的驗證方法不破
  • 的 「非噴射」 只occures,如果我沒有設置的ValidationGroup

回答

1

解決方案:

protected override void OnLoad(System.EventArgs e) 
{ 
    base.OnLoad(e); 
    this.EnsureChildControls(); 
} 

爲什麼呢?
因爲我沒有設置validationGroup,this.EnsureChildControls()將不會被呼叫,除非我打電話在OnLoad

相關問題