Programmatically adding verification control to an asp.net page

I am trying to add a required field program code to an asp.net file. But I get the following error message: Control 'req2' of type 'RequiredFieldValidator' should be placed inside the form tag using runat = server

The C # code I used below is

protected void Page_Load(object sender, EventArgs e)
    {
        RequiredFieldValidator rv = new RequiredFieldValidator();
        rv.ID = "req2";
        rv.ControlToValidate = "TextBox2";
        rv.ErrorMessage = "Data Required";
        this.Controls.Add(rv);
    }

Can someone tell me what's wrong here?

Thank you for sharing your valuable time.

+3
source share
1 answer

Try adding a control to the page form. The reason for this is because you need to add this type of controls to the form.

this.Form.Controls.Add(rv);
+5
source

Source: https://habr.com/ru/post/1726032/


All Articles