How to dynamically add validator controls

Platform: ASP.NET| Category: Controls

VB.NET


Dim i As Integer = 1

’Textbox
Dim txtBox As TextBox = New TextBox
txtBox.ControlStyle.CssClass = 'textbox'
txtBox.ID = 'txtbox' + i.ToString()

’RequiredFieldValidator
Dim rqdVal As RequiredFieldValidator = New RequiredFieldValidator
rqdVal.ID = 'rqdVal' + i.ToString()
rqdVal.ControlToValidate = 'txtbox' + i.ToString()
rqdVal.ErrorMessage = 'Please enter a value'
rqdVal.Display = ValidatorDisplay.Dynamic

’RangeValidator
Dim rngVal As RangeValidator = New RangeValidator
rngVal.ID = 'rngVal' + i.ToString()
rngVal.MinimumValue = '1'
rngVal.MaximumValue = '100'
rngVal.ControlToValidate = 'txtbox' + i.ToString()
rngVal.Type = ValidationDataType.Double
rngVal.ErrorMessage = ' Value should be between 1  and 100'

’Add Controls on the page 
Page.Controls(1).Controls.Add(txtBox)
Page.Controls(1).Controls.Add(rqdVal)
Page.Controls(1).Controls.Add(rngVal)

C#


int i=1;

//Textbox
TextBox txtBox = new TextBox();
txtBox.ControlStyle.CssClass = 'textbox';
txtBox.ID = 'txtbox' + i.ToString();

//RequiredFieldValidator
RequiredFieldValidator  rqdVal = new RequiredFieldValidator();
rqdVal.ID = 'rqdVal' + i.ToString();
rqdVal.ControlToValidate =  'txtbox' + i.ToString();
rqdVal.ErrorMessage = 'Please enter a value';
rqdVal.Display =ValidatorDisplay.Dynamic;

//RangeValidator
RangeValidator rngVal = new RangeValidator();
rngVal.ID = 'rngVal' + i.ToString();
rngVal.MinimumValue = '1';
rngVal.MaximumValue = '100';
rngVal.ControlToValidate = 'txtbox' + i.ToString();
rngVal.Type = ValidationDataType.Double;
rngVal.ErrorMessage = ' Value should be between 1  and 100';

//Add Controls on the page 
Page.Controls[1].Controls.Add (txtBox);
Page.Controls[1].Controls.Add (rqdVal);
Page.Controls[1].Controls.Add (rngVal);

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.