0

我正在向页面以及控件添加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:上面的代码有效。不知道出了什么问题。

4

1 回答 1

1

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

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

希望这可以帮助!!

于 2013-04-11T18:16:35.087 回答