在运行时添加RequiredFieldValidator

时间:2013-04-11 18:11:34

标签: asp.net requiredfieldvalidator

我正在向页面添加控件以及RequiredFieldValidator控件,但出现了问题。

    int i = 4; // for testing; for now
    // add surname textbox
    PlaceHolderResidents.Controls.Add(new LiteralControl("<div class=\"control-group\">"));

    TextBox tb1 = new TextBox();
    tb1.ID = "LastName" + i;
    tb1.CssClass = "input-xlarge";
    labelLastName.AssociatedControlID = tb1.ID;

    PlaceHolderResidents.Controls.Add(labelLastName);
    PlaceHolderResidents.Controls.Add(new LiteralControl("<div class=\"controls\">"));
    PlaceHolderResidents.Controls.Add(tb1);

    RequiredFieldValidator rfv1 = new RequiredFieldValidator();
    rfv1.ControlToValidate = tb1.ID; // ERROR HERE
    rfv1.ErrorMessage = GetLocalResourceObject("RequiredFieldValidator_LastNameResource.ErrorMessage").ToString();
    PlaceHolderResidents.Controls.Add(rfv1);

我收到错误

System.Web.HttpException: Unable to find control id 'LastName4' referenced by the 'ControlToValidate' property of ''.

此代码位于Page_Load(),但我尝试将其置于其他Page个事件中但未成功。有任何想法吗?谢谢。

编辑: 本节的完整代码。

            PlaceHolderResidents.Controls.Add(new LiteralControl("\n\n<div class=\"control-group\">"));
    Label labelLastName = new Label();
    labelLastName.Text = GetLocalResourceObject("LastNameLabelResource.Text").ToString();
    labelLastName.CssClass = "control-label asterisk";
    TextBox tb1 = new TextBox();
    tb1.ID = "LastName" + i;
    tb1.CssClass = "input-xlarge";
    labelLastName.AssociatedControlID = tb1.ID;
    PlaceHolderResidents.Controls.Add(labelLastName);
    PlaceHolderResidents.Controls.Add(new LiteralControl("\n<div class=\"controls\">"));
    PlaceHolderResidents.Controls.Add(tb1);
    PlaceHolderResidents.Controls.Add(new LiteralControl("\n<p class=\"help-block\">"));
    RequiredFieldValidator rfv1 = new RequiredFieldValidator();
    rfv1.ControlToValidate = tb1.ID;
    rfv1.ErrorMessage = GetLocalResourceObject("RequiredFieldValidator_LastNameResource.ErrorMessage").ToString();
    rfv1.EnableClientScript = false;
    PlaceHolderResidents.Controls.Add(rfv1);
    PlaceHolderResidents.Controls.Add(new LiteralControl("\n</p></div></div>"));

值得注意的是,我在页面上有更多这些验证器,其中大多数都在工作。如果我在页面上的许多验证器上面注释掉代码(由于某种原因,还有另一个RequiredFieldValidator出现相同的错误。)

编辑2:上面的代码有效。不确定是什么问题。

1 个答案:

答案 0 :(得分:1)

据我所知,您无法直接访问它。您可能必须使用“FindControl()”方法,如下所示。

RequiredFieldValidator rfv1 = new RequiredFieldValidator();
rfv1.ControlToValidate = PlaceHolderResidents.FindControl(tb1.ID);

希望这有助于!!