【问题标题】:Dynamically creating CustomValidator in server control在服务器控件中动态创建 CustomValidator
【发布时间】:2012-04-20 05:38:33
【问题描述】:

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

无法找到由 '' 的 '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
  • 是的,确实如此。 public class RichTextEditor : RadEditor {}

标签: c# asp.net telerik custom-validators naming-containers


【解决方案1】:

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

我使用的技巧是选择像"." 这样的特殊ID 来表示父控件本身:

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

然后使用"." 作为ControlToValidate

validator.ControlToValidate = "."; 

【讨论】:

  • 太棒了。完美运行。
  • 添加一个“..”来引用父级。说不定哪天有用。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 2018-04-26
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多