[英]Dynamically creating CustomValidator in server control
I have a custom server control which wraps a RadEditor (basically a textarea).我有一个自定义服务器控件,它包装了一个 RadEditor(基本上是一个文本区域)。 I am trying to add a CustomValidator to it dynamically, but I keep getting this error on initial pageload
我正在尝试动态地向其添加 CustomValidator,但我在初始页面加载时不断收到此错误
Unable to find control id 'RadEditor1' referenced by the 'ControlToValidate' property of ''.
无法找到“”的“ControlToValidate”属性引用的控件 ID“RadEditor1”。
This is the code I'm using inside my server control to create the CustomValidator:这是我在服务器控件中用来创建 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
.问题在于
RadEditor
实现了INamingContainer
,因此 ASP.NET 最终在服务器控件的子控件中搜索名为RadEditor1
的控件。 Of course, it's unsuccessful because RadEditor1
doesn't have a child control named RadEditor1
.当然,它不成功,因为
RadEditor1
没有名为RadEditor1
的子控件。
The trick I use is to choose a special ID like "."
我使用的技巧是选择一个特殊的 ID,例如
"."
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
:作为
ControlToValidate
:
validator.ControlToValidate = ".";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.