سؤال

I have a custom server control which wraps a RadEditor (basically a textarea). I am trying to add a CustomValidator to it dynamically, but I keep getting this error on initial pageload

Unable to find control id 'RadEditor1' referenced by the 'ControlToValidate' property of ''.

This is the code I'm using inside my server control to create the CustomValidator:

protected override void OnInit(EventArgs e)
{
    var validator = new CustomValidator();
    validator.CssClass = "validator-error";
    validator.Display = ValidatorDisplay.Dynamic;
    validator.ControlToValidate = this.ID;
    validator.Text = "You've exceeded the maximum allowed length for this field";
    validator.ClientValidationFunction = "checkLength";

    this.Controls.Add(validator);

    base.OnInit(e);
}
هل كانت مفيدة؟

المحلول

The problem is that RadEditor implements INamingContainer, so ASP.NET winds up searching among your server control's children for a control named RadEditor1. Of course, it's unsuccessful because RadEditor1 doesn't have a child control named RadEditor1.

The trick I use is to choose a special ID like "." to mean the parent control itself:

protected override Control FindControl(string id, int pathOffset)
{
    return (id == ".") ? this : base.FindControl(id, pathOffset);
}

Then use "." as the ControlToValidate:

validator.ControlToValidate = "."; 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top