Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding validation control to asp.net page

I am trying to add a required fields validator programmatically in asp.net. But I get the following error message - Control 'req2' of type 'RequiredFieldValidator' must be placed inside a form tag with runat=server

The c# code i have used is below -

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);
    }

Could someone tell me whats gone wrong here?

Thanks for sharing your valuable time.

like image 675
IrfanRaza Avatar asked Feb 10 '26 07:02

IrfanRaza


1 Answers

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

this.Form.Controls.Add(rv);
like image 52
Remco Eissing Avatar answered Feb 15 '26 19:02

Remco Eissing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!