Server Control
Server Control
ASP.NET provides a rich set of web server controls. They provide more functionality compare to HTML server
controls.
Properties of web server control:
• Runs on the web server.
• All ASP.NET server control have runat="server" attribute, by default.
• Server controls provide state management.
• Its execution is slow compare to HTML control.
• You can access these controls from code-behind.
• Server controls have predefined classes.
• Controls are inherited from System.Web.UI.WebControls name space.
Types of server control:
• Standard Controls
• Buttons, input fields, and labels etc.
• Validation Controls
• RequiredFieldValidator
• RangeValidator
• RegularExpressionValidator
• CompareValidator
• CustomValidator
• ValidationSummary
• Rich Controls
• Calendars, file upload, Ad-rotator, and multistep wizards etc.
• Data Controls
• GridView, DetailView, FormView, ListView, Chart, etc.
• Navigation Controls
• Menu, TreeView, SiteMapPath.
• Login Controls
• Login, CreateUserWizard, LoginName, etc.
When a user request a web page, then web server process the page by executing different events. The following
are the various events of ASP.Net page life cycle.
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.
1)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
Example
// WebControls.aspx
// 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 SubmitButton_Click(object sender, EventArgs e)
12. {
13. userInput.Text = UserName.Text;
14. }
15. }
16. }
❖ ASP.NET provides the following list controls.
• Drop-down list
• List box
• Radio button list
• Check box list
• Bulleted list
These controls display list of options to select. You can select one or more options, the choice depends upon
control. They all derive from the System.Web.UI.WebControls.ListControl class
Some of the important common properties of list controls are as follows:
• SelectedValue: Get the value of the selected item from the dropdown list.
• SelectedIndex: Gets the index of the selected item from the dropdown box.
• SelectedItem: Gets the text of selected item from the list.
• Items: Gets the collection of items from the dropdown list.
• DataTextField: Name of the data source field to supply the text of the items. Generally this field came
from the datasource.
• DataValueField: Name of the data source field to supply the value of the items. This is not visible field
to list controls, but you can use it in the code.
• DataSourceID: ID of the datasource control to provide data.
There are several ways through which you can populate these controls such as:
• By using data from database.
• Directly write code to add items.
• Add items through the items collection from property window.
• Write HTML to populate these controls.
• Use inbuilt datasource controls.
1)DropDownList control
DropDownList control is used select single option from multiple listed items.
Example
using System;
using System.Collections.Generic;
public partial class ListControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
List<string> cityList = new List<string>();
cityList.Add("Pune");
cityList.Add("Kanpur");
cityList.Add("Jaipur");
cityList.Add("Delhi");
cityList.Add("Agra");
DropDownList1.DataSource = cityList;
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedItem.Text;
}
}
Select the item from the DropDownList, the label control will display the selected item. Please keep in mind that,
you should write code with association with IsPostBack property otherwise you will get the first item of the
DropDownList.
The ListBox control also supports data binding. You can bind the ListBox through coding with database or attach
it with one of the predefined DataSourceControl objects, which contains the items to display in the control.
DataTextField and DataValueField properties are used to bind to the Text and Value field in the data source.
Example
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
public partial class ListControls : System.Web.UI.Page
{
List<string> empList;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
empList = new List<string>();
empList.Add("Raj");
empList.Add("Rajesh");
empList.Add("John");
empList.Add("Elina");
empList.Add("Samy");
empList.Add("Reena");
ListBox1.DataSource = empList;
ListBox1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach(ListItem item in ListBox1.Items)
{
if(item.Selected)
{
sb.Append(item + "</br>");
}
}
Label1.Text = sb.ToString();
}
}
3)RadioButtonList Control
RadioButtonList Control is same as DropDownList but it displays a list of radio buttons that can be
arranged either horizontally or vertically. You can select only one item from the given RadioButtonList of
options. These options are mutually exclusive.
The RadioButtonList control supports three important properties that affect its layout:
4)CheckBoxList Control
CheckBoxList is generally used, when you want to select one or more options from given several choices. Most
of the properties are same as RadioButtonList control, but the main difference is that you can select more than
one item from CheckBoxList control.
The CheckBoxList control is easier for use, when you have set of options of checkboxes.
Example
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
public partial class ListControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> educationList = new List<string>();
educationList.Add("MBA");
educationList.Add("MCA");
educationList.Add("BE");
educationList.Add("B.Tech");
educationList.Add("B.Arch");
educationList.Add("PHD");
CheckBoxList1.DataSource = educationList;
CheckBoxList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
sb.Append("</br>"+item );
}
}
Label1.Text ="You have selected :"+ sb.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
if (CheckBoxList1.RepeatDirection == RepeatDirection.Vertical)
{
CheckBoxList1.RepeatDirection = RepeatDirection.Horizontal;
}
else
{
CheckBoxList1.RepeatDirection = RepeatDirection.Vertical;
}
}
}
5)BulletedList Control
BulletedList control is very rich in displaying the items in different styles. It dispalys the list either in unordered
or ordered list. Each list item can be rendered as plain text, a LinkButton control, or a link to another web page.
BulletedList control supports the BulletStyle property. The default value of BulletStyle property is NotSet and
rendered as in list of bulleted items.
Possible values are as follows:
• Circle
• CustomImage
• Disc
• LowerAlpha
• LowerRoman
• NotSet
• Numbered
• Square
• UpperAlpha
• UpperRoman
BulletedList control also supports the DisplayMode property that is used to modify the appearance of list
items. Possible values are as follows:
• HyperLink
• LinkButton
• Text
Example
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
public partial class ListControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> educationList = new List<string>();
educationList.Add("MBA");
educationList.Add("MCA");
educationList.Add("BE");
educationList.Add("B.Tech");
educationList.Add("B.Arch");
educationList.Add("PHD");
BulletedList1.DataSource = educationList;
BulletedList1.DataBind();
}
}
protected void Style_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Circle":
BulletedList1.BulletStyle = BulletStyle.Circle;
break;
case "Disc":
BulletedList1.BulletStyle = BulletStyle.Disc;
break;
case "Numbered":
BulletedList1.BulletStyle = BulletStyle.Numbered;
break;
case "Square":
BulletedList1.BulletStyle = BulletStyle.Square;
break;
case "LowerRoman":
BulletedList1.BulletStyle = BulletStyle.LowerRoman;
break;
case "UpperAlpha":
BulletedList1.BulletStyle = BulletStyle.UpperAlpha;
break;
}
}
}
3)FileUpload:
It is an input controller which is used to upload file to the server. It creates a browse button on the form that pop
up a window to select the file from the local machine.
To implementFileUpload 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:FileUpload ID="FileUpload1" runat="server"/>
Server renders it as the HTML control and produces the following code to the browser.
ADVERTISEMENT
1. <input name="FileUpload1" id="FileUpload1" type="file">
This control has its own properties that are tabled below.
Property Description
Example
Here, we are implementing file upload control in web form.
// 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. <p>Browse to Upload File</p>
12. <asp:FileUpload ID="FileUpload1" runat="server" />
13. </div>
14. <p>
15. <asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="Button1_Click" />
16. </p>
17. </form>
18. <p>
19. <asp:Label runat="server" ID="FileUploadStatus"></asp:Label>
20. </p>
21. </body>
22. </html>
Code
// 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 System.Web.UI.HtmlControls.HtmlInputFile File1;
12. protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
13. protected void Page_Load(object sender, EventArgs e)
14. {
15. }
16. protected void Button1_Click(object sender, EventArgs e)
17. {
18. if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
19. {
20. string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
21. string SaveLocation = Server.MapPath("upload") + "\\" + fn;
22. try
23. {
24. FileUpload1.PostedFile.SaveAs(SaveLocation);
25. FileUploadStatus.Text = "The file has been uploaded.";
26. }
27. catch (Exception ex)
28. {
29. FileUploadStatus.Text = "Error: " + ex.Message;
30. }
31. }
32. else
33. {
34. FileUploadStatus.Text = "Please select a file to upload.";
35. }
36. }
37. }
38. }
4)LinkButton:
The LinkButton control is used to create a hyperlink-style button on the Web page. This control looks like a
Hyperlink control but almost has the functionality of the Button control. Despite being a hyperlink, you can't
specify the target URL. There is no UserSubmitBehavior property like the Button control with this control.
Some of the important properties of LinkButton Control are:
CausesValidation: This indicates whether validation will be performed when this button will be clicked.
Here, the Value can be set as true or false.
PostBackUrl: This Specifies the URL of the page to post to from the current page when the LinkButton
control is clicked.
ValidationGroup: The group of controls for which the LinkButton control causes validation when it posts
back to the server.
OnClick: Attach a server side method that will fire when this button will be clicked.
OnClientClick: Attach a client side (JavaScript) method that will fire when this button will be clicked.
LinkButtonExample.aspx
1. <%@ Page Language="C#" AutoEventWireup="true"
2. CodeBehind="LinkButtonExample.aspx.cs" Inherits="LinkButtonExample.LinkButtonExample" %>
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>It is a hyperlink style button</p>
12. </div>
13. <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">javatpoint<
/asp:LinkButton>
14. <p>
15. <asp:Label ID="Label1" runat="server"></asp:Label>
16. </p>
17. </form>
18. </body>
19. </html>
Code
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 LinkButtonExample
8. {
9. public partial class LinkButtonExample : System.Web.UI.Page
10. {
11. protected void LinkButton1_Click(object sender, EventArgs e)
12. {
13. Label1.Text = "Welcome to the javatpoint";
14. }
15. }
16. }
5)Imagemap:
ImageMap control is used to create an image that contains clickable hotspot region. When user click on
the region, the user is either sent to a URL or a sub program is called. When it is rendered on the page, it is
implemented through <img /> HTML tag.
Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are
implemented through style properites of <img>.
HotSpotMode PostBack/Navigate .... When Navigate, the user is navigated to a different URL. In case of
PostBack, the page is posted back to the server.
OnClick Attach a server side event that fires after clicking on image when HostSpotMode is
PostBack.
PostBackValue You can access it in the server side click event through ImageMapEventArgs. (eg.
e.PostBackValue)
6)Image:
The Image control lets you display a picture as part of the data in a form. For example, you might use
an Image to display employee photographs in a personnel form.
The Image control supports the following properties (this is not a complete list):
• AlternateText — Enables you to provide alternate text for the image (required for
accessibility).
• DescriptionUrl — Enables you to provide a link to a page that contains a detailed description
of the image (required to make a complex image accessible).
• GenerateEmptyAlternateText — Enables you to set the AlternateText property to an empty
string.
• ImageAlign — Enables you to align the image relative to other HTML elements in the page.
Possible values are AbsBottom, AbsMiddle, Baseline, Bottom, Left, Middle, NotSet, Right,
TextTop, and Top.
• ImageUrl — Enables you to specify the URL to the image.
7)Image Button:
ImageButton control is generally used to post the form or fire an event either client side or server side.
There is no UserSubmitBehavior property like Button control with LinkButton control.
Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented
through style properites of <input> tag. You can set its Image location either by setting ImageURL properties in the
.aspx page or from server side page. (other properties can also be set from both pages)
Following are some important properties that are very useful.
CausesValidation Value can be set as true/false. This indicates whether validation should be performed when a
button is clicked.
PostBackUrl Indicates the URL on which the Form will be posted back.
ValidationGroup Gets or Sets the name of the validation group that the button belongs to. This is used to validate
only a set of Form controls with a Button.
OnClick Attach a server side method that will fire when button will be clicked.
OnClientClick Attach a client side (javascript) method that will fire when button will be clicked.
8)Calender:
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
NextMonth Text It is used to set text for the next month button.
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. }
15. }
16. }
9)Literal Control:
• The Literal Control is similar to the Label Control as they both are used to display static text on a
web page.
• The Literal Control is not inherited from WebControl namespace.
• The Literal Control doesn't provide substantial functionality but Literal text is programmable.
• It doesn't add any HTML elements to the web page. This control makes it possible to add HTML
code directly in the code designer window without switching to design view and clicking the
HTML button to edit the HTML.
• You cannot apply a style to a literal control.
• Unlike Label control, there is no property like BackColor, ForeColor, BorderColor, BorderStyle,
BorderWidth, Height etc. for Literal control. That makes it more powerful, you can even put a pure
HTML contents into it.
• Literal control is one of the rarely used controls but it is very useful.
• Literal control is light weight control.
• The Literal Control is useful when you want to add text to the output of the page dynamically (from
the server).
• With that you can even programmatically manipulate the Literal text from the code behind.
Mode Description
PassThrough The contents of the control are not modified.
Unsupported markup-language elements are removed from the contents of the control. If
Transform the Literal control is rendered on a browser that supports HTML or XHTML, the control's
contents are not modified.
Listing shows how the Literal Control can be programmable in code behind
1. using System;
2. using System.Configuration;
3. using System.Data;
4. using System.Linq;
5. using System.Web;
6. using System.Web.Security;
7. using System.Web.UI;
8. using System.Web.UI.HtmlControls;
9. using System.Web.UI.WebControls;
10. using System.Web.UI.WebControls.WebParts;
11. using System.Xml.Linq;
12.
13. public partial class _Default : System.Web.UI.Page
14. {
15. protected void Page_Load(object sender, EventArgs e)
16. {
17. Literal1.Mode = LiteralMode.Encode;
18. Literal1.Mode = LiteralMode.PassThrough;
19. Literal1.Mode = LiteralMode.Transform;
20.
21. Literal1.Text = @"<font size=4 color=red>Literal1 with Encode property example</font><script>alert(""
Literal with Encode property"");</script></br></br>";
22. Literal2.Text = @"<font size=4 color=green>Literal2 with PassThrough property example</font><script
>alert(""Literal with PassThrough property"");</script></br></br>";
23. Literal3.Text = @"<font size=4 color=blue>Literal3 with Encode Transform example</font><script>aler
t(""Literal with Transform property"");</script></br></br>";
24. }
25. }
10)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="RadioB
utton1">Male</label>
This control has its own properties that are tabled below.
Property Description
Property Description
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>
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. }