Controls are small functional blocks in a graphical user interface that include text boxes, buttons, check boxes, list boxes, labels, and many other tools. Using these tools, users can enter data, make selections and indicate their preferences.
Controls are also used for structural work such as validation, data access, security, creating master pages and data manipulation.
ASP.NET uses five types of Web controls, which are:
HTML control
HTML server control
ASP.NET Server Controls
ASP.NET Ajax Server Control
User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These controls can be divided into the following categories:
Validation controls - used to validate user input and work by running client-side scripts.
Data Source Control - Provides data binding capabilities to different data sources.
Data View Control - This control is a variety of lists and tables that can display data bound from a data source.
Personalization Controls - Personalize pages based on user information based on user preferences.
Login and security controls - Provides user authentication.
Master Page - Provides a consistent layout and interface across the entire application.
Navigation controls - help users navigate. For example, menu, tree view, etc.
Rich Function Controls - Implement special functions. For example: AdRotator, FileUpload, and Calendar controls.
The basic syntax for using server controls is:
<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />
Additionally, Visual Studio has the following features to help produce error-free code:
Drag and drop controls in Design view.
IntelliSense capabilities for display and autocomplete features.
Properties window for setting property values directly.
ASP.NET server controls with visual capabilities are derived from the WebControl class and inherit all properties, events, and methods of this class.
The WebControl class itself and other server controls that do not have visual capabilities are derived from the System.Web.UI.Control class. For example, PlaceHolder control or XML control.
ASP.Net server controls inherit all properties, events, and methods of the WebControl and System.Web.UI.Control classes.
The following table shows properties common to all server controls:
property | describe |
---|---|
AccessKey | Press this key and the Alt key simultaneously to move focus to the control. |
Attributes | It is a collection of arbitrary properties that do not correspond to control properties (used only for view rendering). |
BackColor | Background color. |
BindingContainer | Contains data-bound controls. |
BorderColor | Border color. |
BorderStyle | Border style. |
BorderWidth | Border width. |
CausesValidation | Shown when verification is caused. |
ChildControlCreated | Indicates whether the child controls of the server control are established. |
ClientID | The control ID of the HTML tag. |
Context | The HttpContext object associated with the server control. |
Controls | A collection of all controls within the control. |
ControlStyle | Styles for web server controls. |
CssClass | CSS classes. |
DataItemContainer | Provides a reference to the namer if it implements an IDataItemContainer. |
DataKeysContainer | Provides a reference for the namer if it implements IDataKeysControl. |
DesignMode | Indicates whether the control is used in the design interface. |
DisabledCssClass | Gets or sets the CSS class to apply to the rendered HTML element when the control is disabled. |
Enabled | Indicates whether the control is disabled. |
EnableTheming | Indicates whether the theme applies to the control. |
EnableViewState | Indicates whether to maintain the view state of the control. |
Events | Gets a list of event handlers representing the control. |
Font | Font settings. |
Forecolor | Foreground color. |
HasAttributes | Indicates whether the control has property groups. |
HasChildViewState | Indicates whether the current server control's child controls have any saved view state settings. |
Height | Height in pixels or percentage. |
ID | The identifier of the control. |
IsChildControlStateCleared | Indicates whether the control contained within this control has control state. |
IsEnabled | Gets a value indicating whether the control is enabled. |
IsTrackingViewState | Indicates whether the server control will save changes to its view state. |
IsViewStateEnabled | Indicates whether view state is enabled for this control. |
LoadViewStateById | Indicates whether the control is participating in loading its view state by ID rather than index. |
Page | The page containing the control. |
Parent | Parental control features. |
RenderingCompatibility | Specifies the version of ASP.NET with which the rendered HTML will be compatible. |
Site | The holder that holds the current control when the design interface is displayed. |
SkinID | Gets or sets the skin applied to the control. |
Style | Gets a collection of text properties that will be displayed as style properties on the external label of the Web server control. |
TabIndex | Gets or sets the index label of the Web server control. |
TagKey | Gets the HtmlTextWriterTag value corresponding to this Web server control. |
TagName | Gets the name of the control label. |
TemplateControl | Contains the template for this control. |
TemplateSourceDirectory | Gets the virtual directory of the page or control contained within this control. |
ToolTip | Gets or sets the text displayed when the mouse pointer is over the Web server control. |
UniqueID | Unique identifier. |
ViewState | Gets a dictionary of state information capable of saving and restoring server control view state across multiple requests to the same page. |
ViewStateIgnoreCase | Indicates whether the StateBag object is case-insensitive. |
ViewStateMode | Gets or sets the view state of this control. |
Visible | Indicates whether the server control is visible. |
Width | Gets or sets the width of the Web server control. |
The server control's methods are presented in the following table:
method | describe |
---|---|
AddAttributesToRender | Add the HTML attributes and styles needed to render the specified HtmlTextWriterTag. |
AddedControl | Called after a child control is added to the control object's controls collection. |
AddParsedSubObject | Notifies the server control that an element, XML or HTML, has been parsed and adds the element to the server control's control collection. |
ApplyStyleSheetSkin | Applies style properties defined in the page style sheet to controls. |
ClearCachedClientID | infrastructure. Set the cached ClientID value to null. |
ClearChildControlState | Removes control state information for child controls of the server control. |
ClearChildState | Removes view state and control state information for all server control child controls. |
ClearChildViewState | Removes view state information for all server control's child controls. |
CreateChildControls | Used to create child controls. |
CreateControlCollection | Create a new control collection to hold child controls. |
CreateControlStyle | Creates a style object that implements all style-related properties. |
DataBind | Bind the data source to the server control and all of its child controls. |
DataBind(Boolean) | Bind the data source and options that raise the DataBinding event to the server control and all of its child controls. |
DataBindChildren | Bind the data source to a child control of the server control. |
Dispose | Enables a server control to perform final cleanup operations before it is released from memory. |
EnsureChildControls | Determines whether the server control contains child controls. If not, create a child control. |
EnsureID | Create an identifier for a control that does not have one. |
Equals(Object) | Determines whether the specified object is equal to the current object. |
Finalize | Allows an object to attempt to release resources and perform other cleanup operations before the object is reclaimed by the Recycle Bin. |
FindControl(String) | Searches the current named container for server controls with the specified id parameter. |
FindControl(String, Int32) | Searches the current named container for server controls with the specified id parameter and integer. |
Focus | Set input focus for the control. |
GetDesignModeState | Gets the control's design-time data. |
GetType | Get the type of the current instance. |
GetUniqueIDRelativeTo | Returns the prefixed portion of the unique ID property of the specified control. |
HasControls | Determines whether the server control contains child controls. |
HasEvents | Indicates whether the event is registered by the control or other child controls. |
IsLiteralContent | Determines whether the server control contains text content only. |
LoadControlState | Restore control state information. |
LoadViewState | Restore view state information. |
MapPathSecure | Retrieves the physical path to which an absolute or relative virtual path is mapped. |
MemberwiseClone | Creates a shallow copy of the current object. |
MergeStyle | Copies any non-blank elements of the Web control with the specified style, but does not overwrite any existing style elements of the control. |
OnBubbleEvent | Determines whether the server control's events pass through the page's UI server control hierarchy. |
OnDataBinding | Raise a data binding event. |
OnInit | Raises the Init event. |
OnLoad | Raises a loading event. |
OnPreRender | Raises the PreRender event. |
OnUnload | Raise an uninstall event. |
OpenFile | Get the stream used to read the file. |
RemovedControl | Called after a child control is removed from the control object's controls collection. |
Render | Displays the control to the specified HTML author. |
RenderBeginTag | Displays the control's HTML opening tag to the specified author. |
RenderChildren | Outputs the content of the server control's children into the provided HtmlTextWriter object to write content that is rendered on the client. |
RenderContents | Displays the content of the control to the specified author. |
RenderControl(HtmlTextWriter) | Outputs the server control content to the provided HtmlTextWriter object and saves tracking information about the control if tracking is enabled. |
RenderEndTag | Displays the control's HTML closing tag to the specified author. |
ResolveAdapter | Gets the control adapter responsible for rendering the specified control. |
SaveControlState | Saves state changes to server controls that have occurred since the page was posted back to the server. |
SaveViewState | Saves any state modified after calling the TrackViewState method. |
SetDesignModeState | Set design-time data for the control. |
ToString | Returns a string representing the current object. |
TrackViewState | Causes a control to track changes to its view state so that they can be stored in the object's ViewState property. |
Let's take a look at a specific server control - the tree view control. Tree view controls are navigation controls. Other navigation controls are: menu control and SiteMapPath control.
Add a tree view control to the page. Select Edit Nodes... from the task and edit each node using the tree view node editor as follows:
After the node is successfully created, the following display will appear in the design view:
The AutoFormat... task allows you to specify the format of the tree view as follows:
Add a label control and text box control on the page and name them respectively lblmessage and txtmessage.
Write a few lines of code to ensure that when a specific node is selected, the label control displays the node text and the text box displays all child nodes below it (if any). The code for the background file should look like this:
using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;namespace eventdemo { public partial class treeviewdemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { txtmessage.Text = " "; } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { txtmessage.Text = " "; lblmessage.Text = "Selected node changed to: " + TreeView1.SelectedNode.Text; TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes; if(childnodes != null) { txtmessage.Text = " "; foreach (TreeNode t in childnodes) { txtmessage.Text += t.Value; } } } }}
Execute the page to see the effect and you will be able to expand and collapse nodes.