2

我在以编程方式将 a 添加RegularExpressionValidator到任何容器控件(面板、占位符等)时遇到问题。这是我的代码:

// 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);都可以正常工作。

有没有办法将我的验证器添加到容器中?我确定我只是做错了什么,或者在某处中间错过了一步。任何帮助将不胜感激。

4

1 回答 1

1

这部分是错误的:

ControlToValidate = control.UniqueID.ToString()

你需要使用这个:

ControlToValidate = control.ID;

您必须先提供一个IDfor 控件。 UniqueID是组件在客户端中的名称,但 Validator Controls 使用服务器端控件名称来执行此操作。

于 2013-05-08T18:29:25.903 回答