RangeValidator Control

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

ASP.

NET Web Forms Label


This control is used to display textual information on the web forms. It is mainly used to
create caption for the other controls like: textbox.
To create label either we can write code or use the drag and drop facility of visual studio
2017.
This is server side control, asp provides own tag to create label. The example is given below.
1. < asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the label.
TabIndex The tab order of the control.
BackColor It is used to set background color of the label.
BorderColor It is used to set border color of the label.
BorderWidth It is used to set width of border of the label.
Font It is used to set font for the label text.
ForeColor It is used to set color of the label text.
Text It is used to set text to be shown for the label.
ToolTip It displays the text when mouse is over the label.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.

Example
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11. .auto-style2 {
12. margin-left: 0px;
13. }
14. .auto-style3 {
15. width: 121px;
16. }
17. </style>
18. </head>
19. <body>
20. <form id="form1" runat="server">
21. <div>
22. <h4>Provide the Following Details:</h4>
23. <table class="auto-style1">
24. <tr>
25. <td class="auto-style3">
26. <asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label>
</td>
27. <td>
28. <asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style2">
</asp:TextBox></td>
29. </tr>
30. <tr>
<td class="auto-style3">

ASP.NET ValidationSummary Control Page 1


31. <td class="auto-style3">
32. <asp:Label ID="Label2" runat="server" Text="Upload a File">
</asp:Label></td>
33. <td>
34. <asp:FileUpload ID="FileUpload1" runat="server" /></td>
35. </tr>
36. </table>
37. </div>
38. </form>
39. </body>
40. </html>
This is a property window of label control.
Output:
Here, we have used label control with two different controls. It produces the following output.

ASP.NET ValidationSummary Control Page 2


16 August 2020
17:43

ASP.NET server controls overview



This article refers to the following Microsoft .NET Framework Class Library namespaces:

• System.Web.UI.HtmlControls.HtmlControl
• System.Web.UI.WebControls.WebControl
Server controls in ASP.NET page framework
The ASP.NET page framework includes a number of built-in server controls that are
designed to provide a more structured programming model for the Web. These controls
provide the following features:

• Automatic state management.


• Simple access to object values without having to use the Request object.
• Ability to react to events in server-side code to create applications that are better
structured.
• Common approach to building user interfaces for web pages.
• Output is automatically customized based on the capabilities of the browser.
In addition to the built-in controls, the ASP.NET page framework also provides the
ability to create user controls and custom controls. User controls and custom controls
can enhance and extend existing controls to build a much richer user interface.
HTML server controls
The HTML server controls are HTML elements that include a runat=server attribute. The
HTML server controls have the same HTML output and the same properties as their
corresponding HTML tags. In addition, HTML server controls provide automatic state
management and server-side events. HTML server controls offer the following
advantages:

• The HTML server controls map one to one with their corresponding HTML tags.
• When the ASP.NET application is compiled, the HTML server controls with
the runat=server attribute are compiled into the assembly.
• Most controls include an OnServerEvent for the most commonly used event for the
control. For example, the <input type=button> control has an OnServerClick event.
• The HTML tags that are not implemented as specific HTML server controls can still
be used on the server side; however, they are added to the assembly
as HtmlGenericControl.
• When the ASP.NET page is reposted, the HTML server controls keep their values.
The System.Web.UI.HtmlControls.HtmlControl base class contains all of the common
properties. HTML server controls derive from this class.
To use an HTML server control, use the following syntax (which uses
the HtmlInputText control as an example):

ASP.NET (C#)Copy
<input type="text" value="hello world" runat=server />

ASP.NET ValidationSummary Control Page 3


• HtmlAnchor Control
• HtmlButton Control
• HtmlForm Control
• HtmlImage Control
• HtmlInputButton Control
• HtmlInputCheckBox Control
• HtmlInputFile Control
• HtmlInputHidden Control
• HtmlInputImage Control
• HtmlInputRadioButton Control
• HtmlInputText Control
• HtmlSelect Control
• HtmlTable Control
• HtmlTableCell Control
• HtmlTableCell Control
• HtmlTextArea Control
Web server controls
Web controls are similar to the HTML server controls such as Button, TextBox, and
Hyperlink, except that Web controls have a standardized set of property names. Web
server controls offer the following advantages:

• Make it easier for manufacturers and developers to build tools or applications that
automatically generate the user interface.
• Simplify the process of creating interactive Web forms, which requires less
knowledge of how HTML controls work and make the task of using them less
prone to errors.
The System.Web.UI.WebControls.WebControl base class contains all of the common
properties. Most of the Web server controls derive from this class.
To use a Web server control, use the following syntax (which uses the TextBox control as
an example):

ASP.NET (C#)Copy
<asp:textbox text="hello world" runat=server />

Web server controls can be divided into four categories:

• Basic Web Controls


• Validation Controls
• List Controls
• Rich Controls
Basic web controls
Basic Web controls provide the same functionality as their HTML server control
counterparts. However, basic Web controls include additional methods, events, and
properties against which you can program.
For more information about individual Web controls that are available in ASP.NET, see
the following Web sites:

Button Web Server Control

ASP.NET ValidationSummary Control Page 4


• Button Web Server Control
• CheckBox Web Server Control
• HyperLink Web Server Control
• Image Web Server Control
• ImageButton Web Server Control
• Label Web Server Control
• LinkButton Web Server Control
• Literal Web Server Control
• Panel Web Server Control
• PlaceHolder Web Server Control
• RadioButton Web Server Control
• Table Web Server Control
• TableCell Web Server Control
• TableRow Web Server Control
• TextBox Web Server Control
Validation controls
Validation controls are used to validate the values that are entered into other controls of
the page. Validation controls perform client-side validation, server-side validation, or
both, depending on the capabilities of the browser in which the page is displayed.
Validation controls offer the following advantages:

• You can associate one or more validation controls with each control that you want
to validate.
• The validation is performed when the page form is submitted.
• You can specify programmatically whether validation should occur, which is useful
if you want to provide a cancel button so that the user can exit without having to
fill valid data in all of the fields.
• The validation controls automatically detect whether validation should be
performed on the client side or the server side.
Note
A client-side validation catches errors before a postback operation is complete.
Therefore, if you have combinations of client-side and server-side validation controls on
a single page, the server-side validation will be preempted if a client-side validation
fails.For more information about individual validation controls that are available in
ASP.NET, refer to the following Web sites:

• RequiredFieldValidator Control
• RangeValidator Control
• CompareValidator Control
• RegularExpressionValidator Control
• CustomValidator Control
• ValidationSummary Control
List controls
List controls are special Web server controls that support binding to collections. You can
use list controls to display rows of data in a customized, template's format. All list
controls expose DataSource and DataMember properties, which are used to bind to
collections.
List controls can bind only to collections that support the IEnumerable, ICollection, or
IListSource interfaces. For example, a Visual C# .NET sample page appears as follows:

ASP.NET ValidationSummary Control Page 5


IListSource interfaces. For example, a Visual C# .NET sample page appears as follows:

ASP.NET (C#)Copy
<%@ Page Language="C#" %>
<script runat="server">
Public void Page_Load()
{
String[] myStringArray = new String[] {"one","two","three"};
rptr.DataSource = myStringArray;
rptr.DataBind();
}
</script>
<html>
<body>
<asp:repeater id=rptr runat="server">
<itemtemplate><%# Container.DataItem %><br></itemtemplate>
</asp:repeater>
</body>
</html>

The output appears as follows:

• one
• two
• three
For more information about individual list controls that are available in ASP.NET, see the
following Web sites:

• ListBox Web Server Control


• CheckBoxList Web Server Control
• RadioButtonList Web Server Control
• Repeater Web Server Control
• DataList Web Server Control
• DataGrid Web Server Control
• DropDownList Web Server Control
Rich controls
In addition to the preceding controls, the ASP.NET page framework provides a few, task-
specific controls called rich controls. Rich controls are built with multiple HTML elements
and contain rich functionality. Examples of rich controls are the Calendar control and the
AdRotator control.
• AdRotator Web Server Control
• Calendar Web Server Control
• Xml Web Server Control
User controls
Often, you may want to reuse the user interface of your Web Form without having to
write any extra code. ASP.NET enables you to do this by converting your Web Forms
into user controls. User controls, which have the.ascx file extension, can be used multiple
times within a single Web Form.
To convert a Web Form into a user control, follow these steps:

1. Remove all <html>, <head>, <body>, and <form> tags.


2. If the @ Page directive appears in the page, change it to @ Control.
3. Include a className attribute in the @ Control directive so that the user control is
typed strongly when you instantiate it.

ASP.NET ValidationSummary Control Page 6


typed strongly when you instantiate it.
4. Give the control a descriptive file name, and change the file extension from .aspx
to .ascx.
Custom controls
In addition to the built-in Web controls, ASP.NET also allows you to create your own
custom controls. It may be useful to develop custom controls if you are faced with one
of these scenarios:

• You need to combine the functionality of two or more built-in Web controls.
• You need to extend the functionality of a built-in control.
• You need a control that is different than any of the controls that currently exist.
For more information about developing custom controls, see the following topics:

• Developing ASP.NET Server Controls


• Developing Custom Controls: Key Concepts
• Developing a Composite Control

ASP.NET ValidationSummary Control Page 7


16 August 2020
17:57

ASP.NET Page Lifecycle


In ASP.NET, a web page has execution lifecycle that includes various phases. These phases
include initialization, instantiation, restoring and maintaining state etc. it is required to
understand the page lifecycle so that we can put custom code at any stage to perform our
business logic.

Page Lifecycle stages


The following table contains the lifecycle stages of ASP.NET web page.
Stage Description
Page This stage occurs before the lifecycle begins. When a page is requested by the
request user, ASP.NET parses and compiles that page.
Start In this stage, page properties such as Request and response are set. It also
determines the Request type.
Initialization In this stage, each control's UniqueID property is set. Master page is applied to
the page.
Load During this phase, if page request is postback, control properties are loaded
with information.
Postback In this stage, event handler is called if page request is postback. After that, the
event Validate method of all validator controls is called.
handling
Rendering Before rendering, view state is saved for the page and all controls. During the
rendering stage, the page calls the Render method for each control, providing a
text writer that writes its output to the OutputStream object of the page's
Response property.
Unload At this stage the requested page has been fully rendered and is ready to
terminate.at this stage all properties are unloaded and cleanup is performed.
A requested page first loaded into the server memory after that processes and sent to the
bowser. At last it is unloaded from the server memory. ASP.NET provides methods and events
at each stage of the page lifecycle that we can use in our application. In the following table,
we are tabled events.

ASP.NET Life Cycle Events


Page Event Typical Use
PreInit This event is raised after the start stage is complete and before the
initialization stage.
Init This event occurs after all controls have been initialized.
We can use this event to read or initialize control properties.
InitComplete This event occurs at the end of the page's initialization stage.
We can use this event to make changes to view state that we want to make
sure are persisted after the next postback.
PreLoad This event is occurs before the post back data is loaded in the controls.
Load This event is raised for the page first time and then recursively for all child
controls.
Control events This event is used to handle specific control events such as Button control'
Click event.
LoadComplete This event occurs at the end of the event-handling stage.
We can use this event for tasks that require all other controls on the page be
loaded.
PreRender This event occurs after the page object has created all controls that are
required in order to render the page.
PreRenderCom This event occurs after each data bound control whose DataSourceID
plete property is set calls its DataBind method.
SaveStateCom It is raised after view state and control state have been saved for the page

ASP.NET ValidationSummary Control Page 8


SaveStateCom It is raised after view state and control state have been saved for the page
plete and for all controls.
Render This is not an event; instead, at this stage of processing, the Page object
calls this method on each control.
Unload This event raised for each control and then for the page.

ASP.NET ValidationSummary Control Page 9


16 August 2020
17:59

ASP.NET Web Forms


Web Forms are web pages built on the ASP.NET Technology. It executes on the server and
generates output to the browser. It is compatible to any browser to any language supported
by .NET common language runtime. It is flexible and allows us to create and add custom
controls.
We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development
Environment) that allows us to drag and drop server controls to the web forms. It also allows
us to set properties, events and methods for the controls. To write business logic, we can
choose any .NET language like: Visual Basic or Visual C#.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code
behind the form, which resides in a separate class file.

Fig: This diagram shows the components of the ASP.NET


The main purpose of Web Forms is to overcome the limitations of ASP and separate view from
the application logic.
ASP.NET provides various controls like: server controls and HTML controls for the Web
Forms. We have tables all these controls below.

Server Controls
The following table contains the server-side controls for the Web Forms.
Control Applicable Events Description
Name
Label None It is used to display text on the HTML
page.
TextBox TextChanged It is used to create a text input in the
form.
Button Click, Command It is used to create a button.
LinkButt Click, Command It is used to create a button that looks
on similar to the hyperlink.
ImageBu Click It is used to create an imagesButton.
tton Here, an image works as a Button.
Hyperlin None It is used to create a hyperlink control
k that responds to a click event.
DropDow SelectedIndexChanged It is used to create a dropdown list
nList control.
ListBox SelectedIndexCnhaged It is used to create a ListBox control like
the HTML control.
DataGrid CancelCommand, EditCommand, It used to create a frid that is used to
DeleteCommand, ItemCommand, show data. We can also perform paging,

ASP.NET ValidationSummary Control Page 10


DeleteCommand, ItemCommand, show data. We can also perform paging,
SelectedIndexChanged, sorting, and formatting very easily with
PageIndexChanged, SortCommand, this control.
UpdateCommand, ItemCreated,
ItemDataBound
DataList CancelCommand, EditCommand, It is used to create datalist that is non-
DeleteCommand, ItemCommand, tabular and used to show data.
SelectedIndexChanged,
UpdateCommand, ItemCreated,
ItemDataBound
Repeater ItemCommand, ItemCreated, It allows us to create a non-tabular type
ItemDataBound of format for data. You can bind the
data to template items, which are like
bits of HTML put together in a specific
repeating format.
CheckBo CheckChanged It is used to create checkbox.
x
CheckBo SelectedIndexChanged It is used to create a group of check
xList boxes that all work together.
RadioBut CheckChanged It is used to create radio button.
ton
RadioBut SelectedIndexChanged It is used to create a group of radio
tonList button controls that all work together.
Image None It is used to show image within the
page.
Panel None It is used to create a panel that works
as a container.
PlaceHol None It is used to set placeholder for the
der control.
Calendar SelectionChanged, VisibleMonthChanged, It is used to create a calendar. We can
DayRender set the default date, move forward and
backward etc.
AdRotato AdCreated It allows us to specify a list of ads to
r display. Each time the user re-displays
the page.
Table None It is used to create table.
XML None It is used to display XML documents
within the HTML.
Literal None It is like a label in that it displays a
literal, but allows us to create new
literals at runtime and place them into
this control.

HTML Controls
These controls render by the browser. We can also make HTML controls as server control. we
will discuss about this in further our tutorial.
Controls Description
Name
Button It is used to create HTML button.
Reset Resets all other HTML form elements on a form to a default value
Button
Submit Automatically POSTs the form data to the specified page listed in the Action
Button attribute in the FORM tag
Text Field Gives the user an input area on an HTML form
Text Area Used for multi-line input on an HTML form
File Field Places a text field and a Browse button on a form and allows the user to select a
file name from their local machine when the Browse button is clicked
Password An input area on an HTML form, although any characters typed into this field are
Field displayed as asterisks

ASP.NET ValidationSummary Control Page 11


Field displayed as asterisks
CheckBox Gives the user a check box that they can select or clear
Radio Used two or more to a form, and allows the user to choose one of the controls
Button
Table Allows you to present information in a tabular format
Image Displays an image on an HTML form
ListBox Displays a list of items to the user. You can set the size from two or more to
specify how many items you wish show. If there are more items than will fit
within this limit, a scroll bar is automatically added to this control.
Dropdown Displays a list of items to the user, but only one item at a time will appear. The
user can click a down arrow from the side of this control and a list of items will be
displayed.
Horizontal Displays a horizontal line across the HTML page
Rule

ASP.NET ValidationSummary Control Page 12


16 August 2020
18:16

ASP.NET Web Forms Server Controls


ASP.NET provides web forms controls that are used to create HTML components. These
controls are categories as server and client based. The following table contains the server
controls for the web forms.
Control Applicable Events Description
Name
Label None It is used to display text on the
HTML page.
TextBox TextChanged It is used to create a text input in
the form.
Button Click, Command It is used to create a button.
LinkButto Click, Command It is used to create a button that
n looks similar to the hyperlink.
ImageBu Click It is used to create an
tton imagesButton. Here, an image
works as a Button.
Hyperlink None It is used to create a hyperlink
control that responds to a click
event.
DropDow SelectedIndexChanged It is used to create a dropdown list
nList control.
ListBox SelectedIndexCnhaged It is used to create a ListBox
control like the HTML control.
DataGrid CancelCommand, EditCommand, It used to create a frid that is used
DeleteCommand, ItemCommand, to show data. We can also perform
SelectedIndexChanged, PageIndexChanged, paging, sorting, and formatting
SortCommand, UpdateCommand, very easily with this control.
ItemCreated, ItemDataBound
DataList CancelCommand, EditCommand, It is used to create datalist that is
DeleteCommand, ItemCommand, non-tabular and used to show data.
SelectedIndexChanged, UpdateCommand,
ItemCreated, ItemDataBound
CheckBo CheckChanged It is used to create checkbox.
x
CheckBo SelectedIndexChanged It is used to create a group of
xList check boxes that all work together.
RadioBut CheckChanged It is used to create radio button.
ton
RadioBut SelectedIndexChanged It is used to create a group of radio
tonList button controls that all work
together.
Image None It is used to show image within the
page.
Panel None It is used to create a panel that
works as a container.
PlaceHol None It is used to set placeholder for the
der control.
Calendar SelectionChanged, VisibleMonthChanged, It is used to create a calendar. We
DayRender can set the default date, move
forward and backward etc.
AdRotato AdCreated It allows us to specify a list of ads
r to display. Each time the user re-

ASP.NET ValidationSummary Control Page 13


AdCreated
r to display. Each time the user re-
displays the page.
Table None It is used to create table.
XML None It is used to display XML
documents within the HTML.
Literal None It is like a label in that it displays a
literal, but allows us to create new
literals at runtime and place them
into this control.

ASP.NET ValidationSummary Control Page 14


16 August 2020
18:34

ASP.NET Web Forms TextBox


This is an input control which is used to take user input. To create TextBox either we can
write code or use the drag and drop facility of visual studio IDE.
This is server side control, asp provides own tag to create it. The example is given below.
1. < asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>
Server renders it as the HTML control and produces the following code to the browser.
1. <input name="TextBox1" id="TextBox1" type="text">
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
MaxLength It is used to set maximum number of characters that can be entered.
Readonly It is used to make control readonly.

Example
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <asp:Label ID="labelId" runat="server">User Name</asp:Label>
12. <asp:TextBox ID="UserName" runat="server" ToolTip="Enter User Name">
</asp:TextBox>
13. </div>
14. <p>
15. <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButto
n_Click" />
16. </p>
17. <br />
18. </form>
19. <asp:Label ID="userInput" runat="server"></asp:Label>
20. </body>
21. </html>
Code Behind
// WebControls.aspx.cs
1. using System;
2. using System.Collections.Generic;
using System.Linq;

ASP.NET ValidationSummary Control Page 15


3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls
8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. protected void SubmitButton_Click(object sender, EventArgs e)
12. {
13. userInput.Text = UserName.Text;
14. }
15. }
16. }
This is a property window of the TextBox control.

Output:
It produces the following output.

It displays user input, when user submits the input to the server. The following screen shot
taking and showing user input.

ASP.NET ValidationSummary Control Page 16


taking and showing user input.

ASP.NET ValidationSummary Control Page 17


16 August 2020
18:36

ASP.NET Web Forms Button


This control is used to perform events. It is also used to submit client request to the server. To
create Button either we can write code or use the drag and drop facility of visual studio IDE.
This is a server side control and asp provides own tag to create it. The example is given
below.
1. < asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle="Solid" ToolTip="Sub
mit"/>
Server renders it as the HTML control and produces the following code to the browser.
1. <input name="Button1" value="Submit" id="Button1" title="Submit" style="border-
style:Solid;" type="submit">
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.

Example
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <asp:Button ID="Button1" runat="server" Text="Click here" OnClick="Button1
_Click" />
12. </div>
13. </form>
14. <br />
15. <asp:Label ID="Label1" runat="server"></asp:Label>
16. </body>
17. </html>
Code Behind
// WebControls.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls
{

ASP.NET ValidationSummary Control Page 18


8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. protected void Button1_Click(object sender, EventArgs e)
12. {
13. Label1.Text = "You Clicked the Button.";
14. }
15. }
16. }
Output:
It produces the following output.

This button displays a message when clicked, as shown below.

ASP.NET ValidationSummary Control Page 19


16 August 2020
18:39

ASP.NET Web Forms RadioButton


It is an input control which is used to takes input from the user. It allows user to select a
choice from the group of choices.
To create RadioButton we can drag it from the toolbox of visual studio.
This is a server side control and ASP.NET provides own tag to create it. The example is given
below.
1. < asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gender"/>
Server renders it as the HTML control and produces the following code to the browser.
1. <input id="RadioButton1" type="radio" name="gender" value="RadioButton1" />
<labelforlabelfor="RadioButton1">Male</label>
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
GroupName It is used to set name of the radio button group.

Example
In this example, we are creating two radio buttons and putting in a group named gender.
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="ge
nder" />
12. <asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="
gender" />
13. </div>
14. <p>
15. <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1
_Click" style="width: 61px" />
16. </p>
17. </form>
18. <asp:Label runat="server" id="genderId"></asp:Label>
19. </body>
20. </html>
Code Behind
// WebControls.aspx.cs

ASP.NET ValidationSummary Control Page 20


// WebControls.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls
8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. protected void Button1_Click(object sender, EventArgs e)
12. {
13. genderId.Text = "";
14. if (RadioButton1.Checked)
15. {
16. genderId.Text = "Your gender is "+RadioButton1.Text;
17. }
18. else genderId.Text = "Your gender is "+RadioButton2.Text;
19.
20. }
21. }
22. }
For this control we have set some properties like this:

Output:
It produces the following output to the browser.

It responses back to the client when user select the gender.

ASP.NET ValidationSummary Control Page 21


ASP.NET ValidationSummary Control Page 22
16 August 2020
18:41

ASP.NET Web Forms CheckBox


It is used to get multiple inputs from the user. It allows user to select choices from the set of
choices.
It takes user input in yes or no format. It is useful when we want multiple choices from the
user.
To create CheckBox we can drag it from the toolbox in visual studio.
This is a server side control and ASP.NET provides own tag to create it. The example is given
below.
1. < asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>
Server renders it as the HTML control and produces the following code to the browser.
1. < input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="CheckBox2">
J2EE</label>
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
Checked It is used to set check state of the control either true or false.

Example
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <h2>Select Courses</h2>
12. <asp:CheckBox ID="CheckBox1" runat="server" Text="J2SE" />
13. <asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE" />
14. <asp:CheckBox ID="CheckBox3" runat="server" Text="Spring" />
15. </div>
16. <p>
17. <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1
_Click" />
18. </p>
19. </form>
20. <p>
21. Courses Selected: <asp:Label runat="server" ID="ShowCourses"></asp:Label>
22. </p>
23. </body>
</html>

ASP.NET ValidationSummary Control Page 23


24. </html>
Code Behind
// WebControls.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls
8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. protected void Page_Load(object sender, EventArgs e)
12. {
13. ShowCourses.Text = "None";
14. }
15. protected void Button1_Click(object sender, EventArgs e)
16. {
17. var message = "" ;
18. if (CheckBox1.Checked)
19. {
20. message = CheckBox1.Text+" ";
21. }
22. if (CheckBox2.Checked)
23. {
24. message += CheckBox2.Text + " ";
25. }
26. if (CheckBox3.Checked)
27. {
28. message += CheckBox3.Text;
29. }
30. ShowCourses.Text = message;
31. }
32. }
33. }

Initially, there is no course selected then it shows none. It displays user selection as shown in
the following screenshot.

ASP.NET ValidationSummary Control Page 24


16 August 2020
18:42

ASP.NET Web Forms RadioButton


It is an input control which is used to takes input from the user. It allows user to select a
choice from the group of choices.
To create RadioButton we can drag it from the toolbox of visual studio.
This is a server side control and ASP.NET provides own tag to create it. The example is given
below.
1. < asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gender"/>
Server renders it as the HTML control and produces the following code to the browser.
1. <input id="RadioButton1" type="radio" name="gender" value="RadioButton1" />
<labelforlabelfor="RadioButton1">Male</label>
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
GroupName It is used to set name of the radio button group.

Example
In this example, we are creating two radio buttons and putting in a group named gender.
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="ge
nder" />
12. <asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="
gender" />
13. </div>
14. <p>
15. <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1
_Click" style="width: 61px" />
16. </p>
17. </form>
18. <asp:Label runat="server" id="genderId"></asp:Label>
19. </body>
20. </html>
Code Behind
// WebControls.aspx.cs

ASP.NET ValidationSummary Control Page 25


// WebControls.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls
8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. protected void Button1_Click(object sender, EventArgs e)
12. {
13. genderId.Text = "";
14. if (RadioButton1.Checked)
15. {
16. genderId.Text = "Your gender is "+RadioButton1.Text;
17. }
18. else genderId.Text = "Your gender is "+RadioButton2.Text;
19.
20. }
21. }
22. }
For this control we have set some properties like this:

Output:
It produces the following output to the browser.

It responses back to the client when user select the gender.

ASP.NET ValidationSummary Control Page 26


ASP.NET ValidationSummary Control Page 27
16 August 2020
18:45

ASP.NET Web Forms Calendar


It is used to display selectable date in a calendar. It also shows data associated with specific
date. This control displays a calendar through which users can move to any day in any year.
We can also set Selected Date property that shows specified date in the calendar.
To create Calendar we can drag it from the toolbox of visual studio.
This is a server side control and ASP.NET provides own tag to create it. The example is given
below.
1. < asp:CalendarID="Calendar1" runat="server" SelectedDate="2017-06-15" >
</asp:Calendar>
Server renders it as the HTML control and produces the following code to the browser.
1. <table id="Calendar1" cellspacing="0" cellpadding="2" title="Calendar"
2. style="border-width:1px;border-style:solid;border-collapse:collapse;">
3. <tr><td colspan="7" style="background-color:Silver;">
4. <table cellspacing="0" style="width:100%;border-collapse:collapse;">
5. <tr><td style="width:15%;">
6. <a href="javascript:__doPostBack('Calendar1','V6330')"
7. style="color:Black" title="Go to the previous month"></a> ...
This control has its own properties that are tabled below.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
NextMonth Text It is used to set text for the next month button.
TitleFormat It sets format for month title in header.
DayHeaderStyle It is used to set style for the day header row.
DayStyle It is used to apply style to days.
NextPrevStyle It is used to apply style to the month navigation buttons.

Calendar Property Window

ASP.NET ValidationSummary Control Page 28


Calendar Property Window

Example
In this example, we are implementing calendar and displaying user selected date to the web
page.
// WebControls.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
2. Inherits="WebFormsControlls.WebControls" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <h2>Select Date from the Calender</h2>
11. <div>
12. <asp:Calendar ID="Calendar1" runat="server"
13. OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
14. </div>
15. </form>
16. <p>
17. <asp:Label runat="server" ID="ShowDate" ></asp:Label>
18. </p>
19. </body>
20. </html>
Code Behind
// WebControls.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace WebFormsControlls
8. {
9. public partial class WebControls : System.Web.UI.Page
10. {
11. public void Calendar1_SelectionChanged(object sender, EventArgs e)
12. {
13. ShowDate.Text = "You Selected: "+Calendar1.SelectedDate.ToString("D");
14. }
}

ASP.NET ValidationSummary Control Page 29


15. }
16. }
Output:
This view shows calendar to the browser.

It shows date selected by the user at the web page. A screenshot is attached below.

ASP.NET ValidationSummary Control Page 30


16 August 2020
18:50

ASP.NET DataList
The ASP.NET DataList control is a light weight server side control that works as a container for
data items. It is used to display data into a list format to the web pages.
It displays data from the data source. The data source can be either a DataTable or a table
from database.
Here, first, we are creating DataList that gets data from a DataTable. This example includes
the following files.

ASP.NET DataList Example with DataTable


// DataListExample2.aspx
1. <%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataListExample2.aspx.cs"
2. Inherits="DataListExample.DataListExample2" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <p>The DataList shows data of DataTable</p>
12. </div>
13. <asp:DataList ID="DataList1" runat="server">
14. <ItemTemplate>
15. <table cellpadding="2" cellspacing="0" border="1" style="width: 300px; height: 1
00px;
16. border: dashed 2px #04AFEF; background-color: #FFFFFF">
17. <tr>
18. <td>
19. <b>ID: </b><span class="city"><%# Eval("ID") %></span>
<br />
20. <b>Name: </b><span class="postal"><%# Eval("Name") %>
</span><br />
21. <b>Email: </b><span class="country"><%# Eval("Email")%>
</span><br />
22. </td>
23. </tr>
24. </table>
25. </ItemTemplate>
26. </asp:DataList>
27. </form>
28. </body>
29. </html>

CodeBehind
// DataListExample2.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Data;
4. using System.Linq;
5. using System.Web;
6. using System.Web.UI;
7. using System.Web.UI.WebControls;
8. namespace DataListExample
9. {
10. public partial class DataListExample2 : System.Web.UI.Page
11. {
protected void Page_Load(object sender, EventArgs e)

ASP.NET ValidationSummary Control Page 31


12. protected void Page_Load(object sender, EventArgs e)
13. {
14. DataTable table = new DataTable();
15. table.Columns.Add("ID");
16. table.Columns.Add("Name");
17. table.Columns.Add("Email");
18. table.Rows.Add("101", "Sachin Kumar", "sachin@example.com");
19. table.Rows.Add("102", "Peter", "peter@example.com");
20. table.Rows.Add("103", "Ravi Kumar", "ravi@example.com");
21. table.Rows.Add("104", "Irfan", "irfan@example.com");
22. DataList1.DataSource = table;
23. DataList1.DataBind();
24. }
25. }
26. }
Output:
It produces the following output to the browser.

ASP.NET DataList Example with database


This example gets data from the database table and includes the following steps.
1) Add a Web Form
Add a web form to drag the DataList over it as we did in the following screen shot.

Select DataList from the data category of the toolbox.

ASP.NET ValidationSummary Control Page 32


Drag the DataList to the form. After dragging, it looks like the following.

Now, we need to configure database connection. Click on it and set new data source.

It will pop up a new window with various Data Sources. Select SQL database and click ok.

ASP.NET ValidationSummary Control Page 33


It will pop up a new window with various Data Sources. Select SQL database and click ok.

After selecting Data Source, now, we need to select data connection. But before proceeding
further add connection string to the web.config file.
// web.config
1. <connectionStrings>
2. <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalD
B;
3. AttachDbFilename=|DataDirectory|\aspnet-AdoNetExample-20170712102014.mdf;
4. Initial Catalog=aspnet-AdoNetExample-20170712102014;Integrated Security=True"
5. providerName="System.Data.SqlClient" />
6. <add name="StudentConnectionString"
7. connectionString="Data Source=DESKTOP-
EDFPJEL;Initial Catalog=Student;Integrated Security=True"
8. providerName="System.Data.SqlClient" />
9. </connectionStrings>
Data Source is the name of the connection that is required to connect SQL Server. It can be
different for other computer systems.

After clicking next, it asks to configure select statement.

ASP.NET ValidationSummary Control Page 34


It allows us to select number of columns to fetch custom record. It also provides * option to
select all columns records.
Now, test the configured query, is it working or not, as we did in the below screenshot.

After finishing configuration, our DataList looks like this:

ASP.NET ValidationSummary Control Page 35


After finishing configuration, our DataList looks like this:

This "DataListExample.aspx" file contains the following code.


1. <%@ Page Language="C#" AutoEventWireup="true"
2. CodeBehind="DataListExample.aspx.cs" Inherits="AdoNetExample.DataListExample" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
13. <ItemTemplate>
14. name:
15. <asp:Label ID="nameLabel" runat="server" Text='<%# Eval("name") %>' />
16. <br />
17. email:
18. <asp:Label ID="emailLabel" runat="server" Text='<%# Eval("email") %>' />
19. <br />
20. contact:
21. <asp:Label ID="contactLabel" runat="server" Text='<%
# Eval("contact") %>' />
22. <br />
23. <br />
24. </ItemTemplate>
25. </asp:DataList>
26. <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$
27. ConnectionStrings:StudentConnectionString %>"
28. SelectCommand="SELECT * FROM [student]"></asp:SqlDataSource>
29. </form>
30. </body>
31. </html>
Output:
This application produces the following output.

ASP.NET ValidationSummary Control Page 36


This application produces the following output.

ASP.NET ValidationSummary Control Page 37


16 August 2020
18:54

ASP.NET DropDownList
The DropDownList is a web server control which is used to create an HTML Select component.
It allows us to select an option from the dropdown list. It can contain any number of items
ASP.NET provides a tag to create DropDownList for web application. The following is the
Syntax of DropDownList tag.
1. <asp:DropDownList id="DropDownList1" runat="server"
2. DataSource="<% databindingexpression %>"
3. DataTextField="DataSourceField"
4. DataValueField="DataSourceField"
5. AutoPostBack="True|False"
6. OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
7. <asp:ListItem value="value" selected="True|False">
8. Text
9. </asp:ListItem>
10. </asp:DropDownList>

ASP.NET DropDownList Example


We are creating DropDownList by using Visual Studio 2017. This example includes the
following steps.
Create a Web Form
Add a new form by specifying its name.

Initially, it is an empty form. Now, we will add a new DropDownList by dragging it from the
toolbox.

After dragging, our web form looks like the below.

ASP.NET ValidationSummary Control Page 38


Now, to add items to the list, visual studio provides Items property where we can add items.
The property window looks like this.

Click on the items (collection) and it will pop up a new window as given below. Initially, it does
not have any item. It provides add button to add new items to the list.

Adding item to the DropDownList, by providing values to the Text and Value properties.

ASP.NET ValidationSummary Control Page 39


Adding item to the DropDownList, by providing values to the Text and Value properties.

We have added more items to it and now, it looks like the following.

After clicking OK,

DropDownListExample.aspx
1. <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
2. CodeBehind="Default.aspx.cs" Inherits="DropDownListExample._Default" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <p>Select a City of Your Choice</p>
11. <div>
12. <asp:DropDownList ID="DropDownList1" runat="server" >
13. <asp:ListItem Value="">Please Select</asp:ListItem>
14. <asp:ListItem>New Delhi </asp:ListItem>
15. <asp:ListItem>Greater Noida</asp:ListItem>
<asp:ListItem>NewYork</asp:ListItem>

ASP.NET ValidationSummary Control Page 40


16. <asp:ListItem>NewYork</asp:ListItem>
17. <asp:ListItem>Paris</asp:ListItem>
18. <asp:ListItem>London</asp:ListItem>
19. </asp:DropDownList>
20. </div>
21. <br />
22. <asp:Button ID="Button1" runat="server" OnClick="Button1
_Click" Text="Submit" />
23. <br />
24. <br />
25. <asp:Label ID="Label1" runat="server" EnableViewState="False"></asp:Label>
26. </form>
27. </body>
28. </html>
// DropDownListExample.aspx.cs
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace DropDownListExample
8. {
9. public partial class _Default : Page
10. {
11. protected void Page_Load(object sender, EventArgs e)
12. {
13. }
14. protected void Button1_Click(object sender, EventArgs e)
15. {
16. if (DropDownList1.SelectedValue == "")
17. {
18. Label1.Text = "Please Select a City";
19. }
20. else
21. Label1.Text = "Your Choice is: " + DropDownList1.SelectedValue;
22. }
23. }
24. }
Output:

At server side, selected city is fetched and display to the user.

ASP.NET ValidationSummary Control Page 41


ASP.NET ValidationSummary Control Page 42
16 August 2020
18:56

ASP.NET DataGrid
.NET Framework provides DataGrid control to display data on the web page. It was introduced
in .NET 1.0 and now has been deprecated. DataGrid is used to display data in scrollable grid.
It requires data source to populate data in the grid.
It is a server side control and can be dragged from the toolbox to the web form. Data Source
for the DataGrid can be either a DataTable or a database. Let's see an example, how can we
create a DataGrid in our application.
This tutorial contains two examples. One is using the DataTable and second is using the
database to display data into the DataGrid.

ASP.NET DataGrid Example with DataTable


This example uses DataTable to bind data to the DataGrid control.
// DataGridExample2.aspx
1. <%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataGridExample2.aspx.cs" I
nherits="DataGridExample.DataGridExample2" %>
2. <!DOCTYPE html>
3. <html xmlns="http://www.w3.org/1999/xhtml">
4. <head runat="server">
5. <title></title>
6. </head>
7. <body>
8. <form id="form1" runat="server">
9. <div>
10. <p>This DataGrid contains DataTable records </p>
11. <asp:DataGrid ID="DataGrid1" runat="server">
12. </asp:DataGrid>
13. </div>
14. </form>
15. </body>
16. </html>

CodeBehind
// DataGridExample2.aspx.cs
1. using System;
2. using System.Data;
3. namespace DataGridExample
4. {
5. public partial class DataGridExample2 : System.Web.UI.Page
6. {
7. protected void Page_Load(object sender, EventArgs e)
8. {
9. DataTable table = new DataTable();
10. table.Columns.Add("ID");
11. table.Columns.Add("Name");
12. table.Columns.Add("Email");
13. table.Rows.Add("101", "Deepak Kumar", "deepak@example.com");
14. table.Rows.Add("102", "John", "john@example.com");
15. table.Rows.Add("103", "Subramanium Swami", "subramanium@example.com");
16. table.Rows.Add("104", "Abdul Khan", "abdul@example.com");
17. DataGrid1.DataSource = table;
18. DataGrid1.DataBind();
19. }
20. }
21. }
Output:
It produces the following output to the browser.

ASP.NET ValidationSummary Control Page 43


ASP.NET DataGrid Example with Database
This example uses database as a data source to display data to the DataGrid. This example
includes the following steps.
1) Add a web form
Create a new form to drag DataGrid upon it. See, as we did in the following screenshot.

After adding, now, open toolbox and drag DataGrid control to the form.

ASP.NET ValidationSummary Control Page 44


After dragging, initially it looks like the following.

This form contains the following source code at backend.


// DataGridExample.aspx
1. <%@ Page Language="C#" AutoEventWireup="true"
2. CodeBehind="DataGridExample.aspx.cs" Inherits="AdoNetExample.DataGridExample" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <asp:DataGrid ID="DataGrid1" runat="server">
13. </asp:DataGrid>
14. </form>
15. </body>
16. </html>
2) Connect to the Database
In the CodeBehind file, we have code of database connectivity, and binding fetched record to
the DataGrid.
CodeBehind file
// DataGridExample.aspx.cs

ASP.NET ValidationSummary Control Page 45


CodeBehind file
// DataGridExample.aspx.cs
1. using System;
2. using System.Data;
3. using System.Data.SqlClient;
4. namespace AdoNetExample
5. {
6. public partial class DataGridExample : System.Web.UI.Page
7. {
8. protected void Page_Load(object sender, EventArgs e)
9. {
10. using (SqlConnection con = new SqlConnection("data source=.; database=student; i
ntegrated security=SSPI"))
11. {
12. SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
13. DataSet ds = new DataSet();
14. sde.Fill(ds);
15. DataGrid1.DataSource = ds;
16. DataGrid1.DataBind();
17. }
18. }
19. }
20. }

Records in SQL Server Table


A student table contains records that we want to display by using the DataGrid. This table
contains the following records.

Output:
After executing this application, it fetches records from the SQL server and displays to the web
browser.

ASP.NET ValidationSummary Control Page 46


ASP.NET ValidationSummary Control Page 47
16 August 2020
19:00

ASP.NET RangeValidator Control


This validator evaluates the value of an input control to check that the value lies between specified ranges.
It allows us to check whether the user input is between a specified upper and lower boundary. This range can be numbers, alphabetic characters
and dates.
Note: if the input control is empty, no validation will be performed.
The ControlToValidateproperty is used to specify the control to validate. The MinimumValue and MaximumValue properties are used to set
minimum and maximum boundaries for the control.
RangeValidator Properties
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
ControlToValidate It takes ID of control to validate.
ErrorMessage It is used to display error message when validation failed.
Type It is used to set datatype of the control value.
MaximumValue It is used to set upper boundary of the range.
MinimumValue It is used to set lower boundary of the range.

Example
In the following example, we are using RangeValidator to validate user input in specified range.
// RangeValidator.aspx
1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RangeValidator.aspx.cs"
2. Inherits="asp.netexample.RangeValidator" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. height: 82px;
10. }
11. .auto-style2 {
12. width: 100%;
13. }
14. .auto-style3 {
15. width: 89px;
16. }
17. .auto-style4 {
18. margin-left: 80px;
19. }
20. </style>
21. </head>
22. <body>
23. <form id="form1" runat="server">
24. <div class="auto-style1">
25. <p class="auto-style4">
26. Enter value between 100 and 200<br/>
27. </p>
28. <table class="auto-style2">
29. <tr>
30. <td class="auto-style3">
31. <asp:Label ID="Label2" runat="server" Text="Enter a value"></asp:Label>
32. </td>
33. <td>
34. <asp:TextBox ID="uesrInput "runat="server"></asp:TextBox>
35. <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="uesrInput"
36. ErrorMessage="Enter value in specified range" ForeColor="Red" MaximumValue ="199" MinimumValue ="101"
37. SetFocusOnError="True"Type=" Integer"></asp:RangeValidator>
38. </td>
39. </tr>
40. <tr>
41. <td class="auto-style3"> </td>
42. <td>
43. <br/>
44. <asp:Button ID="Button2" runat="server" Text="Save"/>
45. </td>
46. </tr>
47. </table>
48. <br/>
49. <br/>
50. </div>
51. </form>
</body>

ASP.NET ValidationSummary Control Page 48


52. </body>
53. </html>
Output:

It throws an error message when the input is not in range.

ASP.NET ValidationSummary Control Page 49


16 August 2020
19:02

ASP.NET RegularExpressionValidator Control


This validator is used to validate the value of an input control against the pattern defined by a
regular expression.
It allows us to check and validate predictable sequences of characters like: e-mail address,
telephone number etc.
The ValidationExpression property is used to specify the regular expression, this expression
is used to validate input control.
RegularExpression Properties
Property Description
AccessKey It is used to set keyboard shortcut for the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
ErrorMessage It is used to set error message that display when validation fails.
ControlToValidate It takes ID of control to validate.
ValidationExpression It is used to set regular expression to determine validity.

Example
Here, in the following example, we are explaining how to use RegularExpressionValidator
control to validate the user input against the given pattern.
// RegularExpressionDemo.aspx
1. <%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegularExpressionDemo.aspx.
cs"
2. Inherits="asp.netexample.RegularExpressionDemo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <table class="auto-style1">
12. <tr>
13. <td class="auto-style2">Email ID</td>
14. <td>
15. <asp:TextBox ID="username" runat="server"></asp:TextBox>
16. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"Contro
lToValidate="username"
17. ErrorMessage="Please enter valid email" ForeColor="Red"ValidationExpression="\w +([- +.']\w
+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
18. </asp:RegularExpressionValidator>
19. </td>
20. </tr>
21. <tr>
22. <td class="auto-style2"></td>
<td>

ASP.NET ValidationSummary Control Page 50


23. <td>
24. <br/>
25. <asp:Button ID="Button1" runat="server" Text="Save"/>
26. </td>
27. </tr>
28. </table>
29. </div>
30. </form>
31. </body>
32. </html>
Output:
It produces the following output when view in the browser.

It will validate email format as we specified in regular expression. If validation fails, it throws
an error message.

ASP.NET ValidationSummary Control Page 51


16 August 2020
19:04

ASP.NET RequiredFieldValidator Control


This validator is used to make an input control required. It will throw an error if user leaves
input control empty.
It is used to mandate form control required and restrict the user to provide data.
Note: It removes extra spaces from the beginning and end of the input value
before validation is performed.
The ControlToValidateproperty should be set with the ID of control to validate.
RequiredFieldValidator Properties
Property Description
AccessKey It is used to set keyboard shortcut for the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
ErrorMessage It is used to set error message that display when validation fails.
ControlToValidate It takes ID of control to validate.

Example
Here, in the following example, we are explaining RequiredFieldValidator control and
creating to mandatory TextBox controls.
// RequiredFieldValidator.aspx
1. <%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="RequiredFieldValidator.aspx.c
s"
2. Inherits="asp.netexample.RequiredFieldValidator" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11. .auto-style2 {
12. width: 165px;
13. }
14. </style>
15. </head>
16. <body>
17. <form id="form1" runat="server">
18. <div>
19. </div>
20. <table class="auto-style1">
21. <tr>
22. <td class="auto-style2">User Name</td>
23. <td>
24. <asp:TextBox ID="username" runat="server"></asp:TextBox>
25. <asp:RequiredFieldValidatorIDasp:RequiredFieldValidatorID="user" runat="server" Contro
lToValidate="username"

ASP.NET ValidationSummary Control Page 52


25.
lToValidate="username"
26. ErrorMessage="Please enter a user name" ForeColor="Red">
</asp:RequiredFieldValidator>
27. </td>
28. </tr>
29. <tr>
30. <td class="auto-style2">Password</td>
31. <td>
32. <asp:TextBox ID="password" runat="server"></asp:TextBox>
33. <asp:RequiredFieldValidator ID="pass" runat="server" ControlToValidate="password" Erro
rMessage="Please enter a password"
34. ForeColor="Red"></asp:RequiredFieldValidator>
35. </td>
36. </tr>
37. <tr>
38. <td class="auto-style2"> </td>
39. <td>
40. <br/>
41. <asp:Button ID="Button1" runat="server" Text="login"/>
42. </td>
43. </tr>
44. </table>
45. </form>
46. </body>
47. </html>
Output:
It produces the following output when view in the browser.

It throws error messages when user login with empty controls.

ASP.NET ValidationSummary Control Page 53


16 August 2020
19:08

ASP.NET ValidationSummary Control


This validator is used to display list of all validation errors in the web form.
It allows us to summarize the error messages at a single location.
We can set DisplayMode property to display error messages as a list, bullet list or single
paragraph.
ValidationSummary Properties
This control has following properties.
Property Description
AccessKey It is used to set keyboard shortcut for the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
ShowMessageBox It displays a message box on error in up-level browsers.
ShowSummary It is used to show summary text on the form page.
ShowValidationErrors It is used to set whether the validation summary should be shown or
not.

Example
The following example explains how to use ValidationSummery control in the application.
// ValidationSummeryDemo.aspx
1. <%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="ValidationSummery Demo.asp
x.cs"
2. Inherits="asp.netexample.ValidationSummery Demo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <table class="auto-style1">
13. <tr>
14. <td class="auto-style2">User Name</td>
15. <td>
16. <asp:TextBox ID="username" runat="server"></asp:TextBox>
17. <asp:RequiredFieldValidator ID="user" runat="server" ControlToValidate="username"
18. ErrorMessage="Please enter a user name" ForeColor="Red">*</asp:RequiredFieldValidato
r>
19. </td>
20. </tr>
21. <tr>
22. <td class="auto-style2">Password</td>
23. <td>
24. <asp:TextBox ID="password" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="pass" runat="server" ControlToValidate="password"

ASP.NET ValidationSummary Control Page 54


25. <asp:RequiredFieldValidator ID="pass" runat="server" ControlToValidate="password"
26. ErrorMessage="Please enter a password" ForeColor="Red">*</asp:RequiredFieldValidator
>
27. </td>
28. </tr>
29. <tr>
30. <td class="auto-style2">
31. <br/>
32. <asp:Button ID="Button1" runat="server"Text="login"/>
33. </td>
34. <td>
35. <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red"/>
36. <br/>
37. </td>
38. </tr>
39. </table>
40. </form>
41. </body>
42. </html>
Output:
It produces the following output when view in the browser.

It throws error summary when user login without credentials.

ASP.NET ValidationSummary Control Page 55


16 August 2020
19:11

ASP.NET Validation
In this chapter, we will discuss about the data validation in the Web Forms. To perform
validation, ASP.NET provides controls that automatically check user input and require no code.
We can also create custom validation for our application.

ASP.NET validation controls


Following are the validation controls
Validator Description
CompareValidator It is used to compare the value of an input control against a value of
another input control.
RangeValidator It evaluates the value of an input control to check the specified range.
RegularExpressionV It evaluates the value of an input control to determine whether it
alidator matches a pattern defined by a regular expression.
RequiredFieldValida It is used to make a control required.
tor
ValidationSummary It displays a list of all validation errors on the Web page.

ASP.NET CompareValidator Control


This validator evaluates the value of an input control against another input control on the
basis of specified operator.
We can use comparison operators like: less than, equal to, greater than etc.
Note: If the input filed is empty, no validation will be performed.
CompareValidator Properties
Property Description
AccessKey It is used to set keyboard shortcut for the control.
TabIndex The tab order of the control.
BackColor It is used to set background color of the control.
BorderColor It is used to set border color of the control.
BorderWidth It is used to set width of border of the control.
Font It is used to set font for the control text.
ForeColor It is used to set color of the control text.
Text It is used to set text to be shown for the control.
ToolTip It displays the text when mouse is over the control.
Visible To set visibility of control on the form.
Height It is used to set height of the control.
Width It is used to set width of the control.
ControlToCompare It takes ID of control to compare with.
ControlToValidate It takes ID of control to validate.
ErrorMessage It is used to display error message when validation failed.
Operator It is used set comparison operator.

Example
Here, in the following example, we are validating user input by using CompareValidator
controller. Source code of the example is given below.
// compare_validator_demo.aspx
1. <%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="compare_validator_demo.asp
x.cs"
Inherits="asp.netexample.compare_validator_demo" %>

ASP.NET ValidationSummary Control Page 56


2. Inherits="asp.netexample.compare_validator_demo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11. .auto-style2 {
12. height: 26px;
13. }
14. .auto-style3 {
15. height: 26px;
16. width: 93px;
17. }
18. .auto-style4 {
19. width: 93px;
20. }
21. </style>
22. </head>
23. <body>
24. <form id="form1" runat="server">
25. <table class="auto-style1">
26. <tr>
27. <td class="auto-style3">
28. First value</td>
29. <td class="auto-style2">
30. <asp:TextBox ID="firstval" runat="server" required="true"></asp:TextBox>
31. </td>
32. </tr>
33. <tr>
34. <td class="auto-style4">
35. Second value</td>
36. <td>
37. <asp:TextBox ID="secondval" runat="server"></asp:TextBox>
38. It should be greater than first value</td>
39. </tr>
40. <tr>
41. <td class="auto-style4"></td>
42. <td>
43. <asp:Button ID="Button1" runat="server" Text="save"/>
44. </td>
45. </tr>
46. </table>
47. < asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="seco
ndval"
48. ControlToValidate="firstval" Display="Dynamic" ErrorMessage="Enter valid value" ForeColor="
Red"
49. Operator="LessThan" Type="Integer"></asp:CompareValidator>
50. </form>
51. </body>
52. </html>
Output:

ASP.NET ValidationSummary Control Page 57


Output:

ASP.NET ValidationSummary Control Page 58

You might also like