ASP.NET controls(Server control,Html control ,Validation Control)

ASP.NET controls(Server control,Html control ,Validation Control) - contributed by Nihal Singh

.NET Tutorial > ASP.NET Controls

Understanding Controls

There are three families of controls and they are as follows:-

1. HTML Controls:- These are standard controls and they are part of HTML language. These are not classes but they are tags and we can only do client-side programming with them.

2. HTML Server Controls: These are the same as HTML controls but they have runat=server attribute. With the HTML server controls we can do server-side programming. If you want to convert old ASP application into ASP.NET application then HTML server control is used.

3. WEB Controls:
These are .NET classes and they have rich set of properties, methods, and events. They are programmable on client side as well server side.

ASP.NET provides the rich set of controls. These controls can be divided into following groups.

1. Standard Controls
2. Validation Controls
3. Rich Controls
4. Data Controls
5. Navigation Controls
6. Login Controls

Life Cycle of an ASP.NET Web Page

The life cycle starts when a user requests a Web page through the browser. The Web server then processes the page through the step by step events before returning the results back to the user’s browser. These processing stages define the life cycle of a Web page.

Page Life Cycle Events

Event Name Description
PreInit: This event is used if you need to set values such as master page or theme dynamically.
Init: It fires after each control has been initialized. You can use this event to change initialization values for controls.
InitComplete:  This event fires once all initializations of the page and its controls have been completed.
PreLoad: It raises before view state has been loaded for the page and its controls and before PostBack processing. It can be used when you need to write code after the page is initialized but before the view state has been wired back up to the controls.
Load: This event is raised when the web page and its control are initialized. Page load event typically checks for PostBack and then sets control properties appropriately
Contol(Postback) events(s): Any events on the page or its controls thatcaused the PostBack to occur. This might be a button’s click event or some other event.
LoadComplete: In this event all controls are loaded properly.
PreRender: This event takes place before saving ViewState, so any changes made here are saved.
SaveStateComplete: Before this event the view state of the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.
Render: It generates the client-side HTML, (DHTML, and script that are necessary to properly display a control at the browser.
UnLoad This is the last event of ASP.NET web page .You can write cleanup code in this event.

Understanding View State

The HTTP protocol is a stateless protocol. Each time user request a web page from a website, from the website’s perspective, you are a completely new person. View state persist state across postbacks. For example, if you assign a value to a Label control’s Text property, the Label control retains this value across multiple page requests. It is a hidden form field named __VIEWSTATE. This hidden form field contains the value of the control’s property. When the page is posted back to the server, the ASP.NET Framework gets the values of all the properties stored in View State. In this way, the ASP.NET Framework preserves the state of control properties across postbacks to the web server. By default, View State is enabled for every control.

The __VIEWSTATE hidden form field can become very large. Storing too much data into View State can slow down the rendering of a page because the contents of the hidden field must be pushed back and forth between the web server and browser.

You can see how much View State each control contained in a page is consuming by enabling tracing for a page by applying Trace=”true” attribute in its <%@ Page %> directive, which enables tracing.

Understanding the Page.IsPostBack Property

The Page class includes a property called the IsPostBack property, which you can use to detect whether the page has already been posted back to the server. Its return type is bool.Page load event is fire every time when you request a page through the firing of event or some other ways. So if you have done some coding in Page_Load event, it will be initializing every time. If you remove the IsPostBack property from the Page_Load() method, then you will not get the desire result. The DropDownList always displays its first item as the selected item.


public partial class _Default : System.Web.UI.Page
              protected void Page_Load(object sender, EventArgs e)
                            if (!Page.IsPostBack)
                                          // create collection of items
                                          ArrayList items = new ArrayList();

                                          // Bind to DropDownList
                                          DropDownList1.DataSource = items;
                                          DropDownList1.DataBind ();

              protected void Button1_Click(object sender, EventArgs e)
                            Label1.Text = DropDownList1.SelectedItem.Text;


Input Validation

Validation is important part of any web application. Validation controls provide Rapid Application Development (RAD) features for automatically checking the validity of input data. These controls are available in the System.Web.UI.WebControls namespace.

Validation controls are used to:

  • To validate user input data.
  • Data format, data type and data range is used for validation.

Six validation controls are available in the ASP.NET

RequiredFieldValidator : Enables you to require a user to enter a value in a form field.
RangeValidator : Enables you to check whether a value falls between a certain minimum and maximum value
CompareValidator : Enables you to compare a value against another value or perform a data type check.
RegularExpressionValidator : Enables you to compare a value against a regular expression.
CustomValidator : Enables you to perform custom validation.
ValidationSummary : Enables you to display a summary of all validation errors in a page.


You can create a field as a mandatory field by adding a RequiredFieldValidator control to the page and linking it to the required control. For example, you can specify that users must fill in a Name text box before they can submit a registration form.

Property Description
ControlToValidate The ID of the control for which the user must provide a value.
ErrorMessage This property is used to show the error message, If the user forgets to enter the data errors that will appear.


<asp: Textbox id="txtName" runat="server"></asp: Textbox>
<asp: RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="Name is a required field."
</asp: RequiredFieldValidator>


You can perform three different types of validation tasks by using CompareValidator control.

  • To perform a data type check.
  • To compare the value entered into a form field against a fixed value.
  • To compare the value of one form field against another

Property Description
ControlToValidate The ID of the form field being validated.
ErrorMessage Properties that specify error message when validation fails.
ValueToCompare The fixed value against which to compare.
ControlToCompare The ID of a control against which to compare.
Type The type of value being compared. Possible values are String, Integer, Double, Date, and Currency. The values are converted to this type before the comparison is performed.
Operator The type of comparison to perform. Possible values are DataTypeCheck, Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and NotEqual.


<asp: Textbox id="txtAge" runat="server"></asp: Textbox>

<asp: CompareValidator id="CompareFieldValidator1" runat="server"
ErrorMessage="Please enter number greater than zero.">
</asp: CompareValidator >


The RangeValidator control provides the facility to check whether the value of a form field falls between a certain minimum and maximum value. It verifies that user input is within a specified range of values.

Property Description
ControlToValidate The ID of the form field being validated.
ErrorMessage Properties that specify error message when validation fails.
MinimumValue The minimum value of the validation range.
MaximumValue The maximum value of the validation range.
Type The type of comparison to perform. Possible values are String, Integer


<asp: Textbox id="TextBox1"
<asp: RangeValidator id="Range1"
Text="The value must be from 1 to 10!"

Don’t forget to set the Type property when using the RangeValidator control. By default, the Type property has the value String, and the RangeValidator performs a string comparison to determine whether a values falls between the minimum and maximum value.


The RegularExpressionValidator control performs its validation according to the regular expression. A regular expression is a powerful pattern-matching language that can be used to identify simple and complex character sequences. You can check a predefined pattern, such as a phone number, postal code, e-mail address, dates, and so on. The control uses the ValidationExpression property to set a valid regular expression
that is applied to the data that is to be validated.


Text=” (Invalid email)”
Runat=”server” />


The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. This control is particularly useful when working with large forms.
If a user enters the wrong value for a form field located toward the end of the page, then the user might never see the error message. If you use the ValidationSummary control, however, you can always display a list of errors at the top of the form.

Property Description
DisplayMode BulletList, List, and SingleParagraph
HeaderText Display header text above the validation summary.
ShowMessageBox Enables you to display a popup alert box.
ShowSummary Enables you to hide the validation summary in the page.


CustomValidator control enables you to create your own validation and that validation can run with the other validation control on the page. The CustomValidator control performs validation-based code you write. You can write validation code that will be executed on the client side using JavaScript,or with server-side validation .

Custom Client-Side Validation

Client-side validation provides users immediate feedback when they are working with your page.


Define a JavaScript function.The function must have the following method signature:

function MyFuction(source, arguments)

// MyFuction is the user defined function name.

Attach your client-side function to a CustomValidator by setting the ClientValidationFunction property of the CustomValidator control to the name of your validation function.


//Code for Password must be between 6-12 characters

<script language="javascript" type="text/javascript">

function MyFuction (source, arguments)
              var data = arguments.Value.split('');
              //start by setting false
              //check length
              if(data.length < 6 || data.length > 12) return;


Custom Server-Side Validation

If you want to work with CustomValidator control you must override its ServerValidate event.


protected void CustomValidatorNewPassword_ServerValidate(object source, ServerValidateEventArgs args)
              string data = args.Value;
              //start by setting false
              args.IsValid = false;
              //check length
              if (data.Length < 6 || data.Length > 12) return;
                            args.IsValid = true;

Write your comment - Share Knowledge and Experience

Latest MCQs
» General awareness - Banking » ASP.NET » PL/SQL » Mechanical Engineering
» IAS Prelims GS » Java » Programming Language » Electrical Engineering
» English » C++ » Software Engineering » Electronic Engineering
» Quantitative Aptitude » Oracle » English » Finance
Home | About us | Sitemap | Contact us | We are hiring