我遇到了以编程方式将RegularExpressionValidator
添加到任何Container控件(Panel,Placeholder等)的问题。这是我的代码:
// Get the path of the file on the server
string page = Page.Request.FilePath;
int managementCompanyId = Convert.ToInt32(Session["ManagementCompanyId_AddResident"].ToString().Trim());
// Get field validation details
Collection<ExportFieldValidation> details = ValidationBL.GetValidationDetails(managementCompanyId, page);
ContentPlaceHolder body = Page.Form.FindControl("ContentBody") as ContentPlaceHolder;
foreach (ExportFieldValidation detailItem in details)
{
// Check if the control exists on the page
TextBox control = body.FindControl(detailItem.FieldToValidate) as TextBox;
if (control != null)
{
RegularExpressionValidator regex = new RegularExpressionValidator()
{
ControlToValidate = control.UniqueID.ToString(),
ID = detailItem.ValidatorFieldName,
ValidationExpression = detailItem.RegularExpression,
Page = this,
SetFocusOnError = true,
Text = detailItem.ErrorMessage,
Enabled = true,
EnableViewState = true,
CssClass = "Error"
};
Panel validationPanel = body.FindControl("PanelAddResident") as Panel;
validationPanel.Controls.Add(regex);
}
}
当我转到页面时,我收到错误Unable to find control id 'myControl' referenced by the 'ControlToValidate' property of 'RegularExpressionValidatorResidentId'
,其中我的控件是上面的control.UniqueID.ToString()
,我们将其存储在数据库中并且肯定是正确的,因为我已经加倍了,三重和四重检查了价值。
但是,如果我将validationPanel.Controls.Add(regex);
替换为Page.Form.Controls.Add(regex);
,一切都会完美无缺。
有没有办法将验证器添加到容器中?我确定我只是做错了什么或者错过了中间某个地方的一步。任何帮助将不胜感激。
答案 0 :(得分:1)
这部分错了:
ControlToValidate = control.UniqueID.ToString()
你需要使用它:
ControlToValidate = control.ID;
您之前必须提供ID
进行控制。
UniqueID
是组件在客户端中的名称,但Validator Controls使用服务器端控件名称来执行此操作。