Gary King

Gary King

  • NA
  • 83
  • 209.3k

Creating multiple RequiredFieldValidators in Code Behind

Oct 5 2010 10:52 AM

I want to be able to create RequiredFieldValidators in code behind. The controls (to be validated) are created in the code behind which reads the control details from a database - so there could be any number of controls on the page.
So, starting with basics, let's assume that I have 1 DropDownList (myDDL1) on my page. The code would be as follows:
 

RequiredFieldValidator myRFV = new RequiredFieldValidator();
myRFV.ControlToValidate =
"myDDL1";
myRFV.ErrorMessage =
"you must select a value!";
form1.Controls.Add(myRFV);

When there is more than 1 control (eg myDDL1 and myDDL2), then I need to create a different RequiredFieldValidator for each control to be validated. The following code doesn't work - it is just to give a simplified example of what I am trying to achieve. The problem is that I need to be able to dynamically name the requiredFieldValidator - myRFV
Int32 myCount = 1;

RequiredFieldValidator myRFV + myCount = new RequiredFieldValidator(); // myRFV + myCount does not work!!!
myRFV + myCount.ControlToValidate =
"myDDL1";
myRFV + myCount.ErrorMessage =
"you must select a value!";
form1.Controls.Add(myRFV + myCount);
 
 
myCount = 2;

RequiredFieldValidator myRFV + myCount = new RequiredFieldValidator();
myRFV + myCount.ControlToValidate = "myDDL2";
myRFV + myCount.ErrorMessage = "you must select a value!";
form1.Controls.Add(myRFV + myCount);

So, first the RFV control name would be myRFV1 and the second RFV control would be myRFV2.
But C# wont let me create the RFV instances in this way. If I use the same RFV name (myRFV), and only change the .ControlToValidate, then only the second drop down list will get validated.
Thanks
Gary King

Answers (4)