C# 在服务器控件中动态创建CustomValidator

C# 在服务器控件中动态创建CustomValidator,c#,asp.net,telerik,custom-validators,naming-containers,C#,Asp.net,Telerik,Custom Validators,Naming Containers,我有一个自定义服务器控件,它包装了一个RadEditor(基本上是一个文本区域)。我试图动态地向其中添加CustomValidator,但在初始页面加载时不断出现此错误 找不到由引用的控件id“RadEditor1” “”的“ControlToValidate”属性 这是我在服务器控件中用于创建CustomValidator的代码: protected override void OnInit(EventArgs e) { var validator = new CustomValida

我有一个自定义服务器控件,它包装了一个RadEditor(基本上是一个文本区域)。我试图动态地向其中添加CustomValidator,但在初始页面加载时不断出现此错误

找不到由引用的控件id“RadEditor1” “”的“ControlToValidate”属性

这是我在服务器控件中用于创建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);
}

问题在于
RadEditor
实现了
INamingContainer
,因此ASP.NET最终在服务器控件的子控件中搜索名为
RadEditor1
的控件。当然,这是不成功的,因为
RadEditor1
没有名为
RadEditor1
的子控件

我使用的技巧是选择一个特殊的ID,如
,表示父控件本身:

protected override Control FindControl(string id, int pathOffset)
{
    return (id == ".") ? this : base.FindControl(id, pathOffset);
}
然后使用
作为
控件验证

validator.ControlToValidate = "."; 

您的服务器控件是否源于
RadEditor
?是的<代码>公共类RichTextEditor:RadEditor{}
Brilliant。工作完美。添加一个“.”以表示家长。总有一天会有用的。:)