简体   繁体   中英

Add RequiredFieldValidator to dynamically created control in code behind

I have a page with some textboxes. Some of the ASP:Textboxes are made in the .aspx file, and other custom ones are created in codebehind (based on db). I want to validate to make sure all fields are filled.

When I press my ASP:Button to continue, the textboxes created in my html/aspx file are correctly validated, but for some reason, the dynamically created RequiredFieldValidators are ignored.

Code:

                    <tr runat="server" id="weight_row">
                        <td>
                            Weight: <asp:Label runat="server" ID="weightReqLabel" CssClass="required" Visible="false">*</asp:Label>
                        </td>
                        <td>
                            <asp:TextBox runat="server" ID="weight" CssClass="form-control"></asp:TextBox>
                            <asp:RequiredFieldValidator runat="server" ID="validator_weight" ControlToValidate="weight" SetFocusOnError="true" ErrorMessage="Required." CssClass="validation-error"></asp:RequiredFieldValidator>
                        </td>
                    </tr>

The above works correctly.

However, this does not work:

TextBox txtbx = new TextBox();
txtbx.ID = "TextBox_" + i;
txtbx.CssClass = "form-control";
txtbx.Text = fieldValue;

RequiredFieldValidator reqFieldVal = new RequiredFieldValidator();
reqFieldVal.ID = "validator_" + i;
reqFieldVal.ControlToValidate = txtbx.ID;
reqFieldVal.SetFocusOnError = true;
reqFieldVal.ErrorMessage = "Required";
reqFieldVal.EnableClientScript = false;
reqFieldVal.CssClass = "required";
reqFieldVal.Enabled = true;

placeHolder.Controls.Add(txtbx);
placeHolder.Controls.Add(reqFieldVal);

Before I added EnableClientScript=false , none of the validation was working. After I added that, the normally coded validators worked, but the code behind ones do not.

I've also tried to add a ValidationGroup and try Page.Validate in the OnClick of the button but it doesn't seem to help.

protected void SaveAndContinue_Click(object sender, EventArgs e)
{
    Page.Validate();
        if (Page.IsValid)
        {
            ((Redirect))
        }

}

What am I doing wrong?

try this

...
placeHolder.Controls.Add(reqFieldVal); 
reqFieldVal.Validate();
...

it worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM