Friday, 3 February 2012

Advanced Controls | ASP.Net Tutorial | ASP.Net Tutorial PDF

      These controls are advanced in terms of their usage, the HTML code they generate, and the background work they do for you. Some of these controls aren’t available to older versions of ASP.NET; we’ll learn more about many of them (as well as others that aren’t covered in this chapter) as we progress through this book.

Calendar
     The Calendar is a great example of the reusable nature of ASP.NET controls. The Calendar control generates markup that displays an intuitive calendar in which the user can click to select, or move between, days, weeks, months, and so on.
     The Calendar control requires very little customization. In Visual Web Developer, select Website > Add New Item…, and make the changes indicated:

Visual Basic                           LearningASP\VB\Calendar_01.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
Calendar Test
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="myCalendar" runat="server" />
</div>
</form>
</body>
</html>

Again, the C# version is the same, except for the Page declaration:

C#                             LearningASP\CS\01_Calendar.aspx(excerpt)
<%@ Page Language="C#" %>

If you save this page in your working folder and load it, you’ll see the output shown in below Figure.
Figure : Displaying the default calendar

The Calendar control contains a wide range of properties, methods, and events, including those listed in above Table.
Table 4.3. Some of the Calendar control’s properties 
   Let’s take a look at an example that uses some of these properties, events, and methods to create a Calendarcontrol which allows users to select days, weeks, and months. Modify the calendar in Calendar.aspx (both the VB and C# versions), and add a label to it, as follows:
                                                   LearningASP\VB\Calendar_02.aspx(excerpt)

      <form id="form1" runat="server">
      <div>
          <h1>Pick your dates:</h1>
          <asp:Calendar ID="myCalendar" runat="server"
                 DayNameFormat="Short" FirstDayOfWeek="Sunday"
                 NextPrevFormat="FullMonth" SelectionMode="DayWeekMonth"
                 SelectWeekText="Select Week"
                 SelectMonthText="Select Month" TitleFormat="Month"
                OnSelectionChanged="SelectionChanged" />
         <h1>You selected these dates:</h1>
         <asp:Label ID="myLabel" runat="server" />
     </div>
     </form>


Now edit the <script runat="server"> tag to include the SelectionChangedevent handler referenced by your calendar:
Visual Basic                        LearningASP\VB\Calendar_02.aspx(excerpt)
<script runat="server">
Sub SelectionChanged(ByVal s As Object, ByVal e As EventArgs)
myLabel.Text = ""
For Each d As DateTime In myCalendar.SelectedDates
myLabel.Text &= d.ToString("D") & "<br />"
Next
End Sub
</script>

C#                             LearningASP\CS\Calendar_02.aspx(excerpt)
<script runat="server">
void SelectionChanged(Object s, EventArgs e)
{
myLabel.Text = "";
foreach (DateTime d in myCalendar.SelectedDates)
{
myLabel.Text += d.ToString("D") + "<br />";
}
}
</script>

          Save your work and test it in a browser. Try selecting a day, week, or month. The selection will be highlighted in a similar way to the display shown in elow Figure.

                  Figure : Using the Calendar control
  
In SelectionChanged, we loop through each of the dates that the user has selected, and append each to the Label we added to the page.

AdRotator
       The AdRotator control allows you to display a list of banner advertisements at random within your web application. However, it’s more than a mere substitute for creating a randomization script from scratch. Since the AdRotator control gets its content from an XML file, the administration and updating of banner advertisement files and their properties is a snap. Also, the XML file allows you to control the banner’s image, link, link target, and frequency of appearance in relation to other banner ads.

        The benefits of using this control don’t stop there, though. Most of the AdRotator control’s properties reside within an XML file, so, if you wanted to, you could share that XML file on the Web, allowing value added resellers (VARS), or possibly your companies’ partners, to use your banner advertisements on their web sites.
    If you want to test this control out, create a file called ads.xml in your LearningASP\VB or LearningASP\CS folder (or both), and insert the content presented below. Feel free to create your own banners, or to use those provided in the code archive for this book:

LearningASP\VB\Ads.xml
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>workatdorknozzle.gif</ImageUrl>
<NavigateUrl>http://www.example.com</NavigateUrl>
<TargetUrl>_blank</TargetUrl>
<AlternateText>Work at Dorknozzle!</AlternateText>
<Keyword>HR Sites</Keyword>
<Impressions>2</Impressions>
</Ad>
<Ad>
<ImageUrl>getthenewsletter.gif</ImageUrl>
<NavigateUrl>http://www.example.com</NavigateUrl>
<TargetUrl>_blank</TargetUrl>
<AlternateText>Get the Nozzle Newsletter!</AlternateText>
<Keyword>Marketing Sites</Keyword>
<Impressions>1</Impressions>
</Ad>
</Advertisements>

   As you can see, the Advertisements element is the root node, and in accordance with the XML specification, it appears only once. For each individual advertisement, we simply add an Ad child element. For instance, the above advertisement file contains details for two banner advertisements.

    As you’ve probably noticed by now, the .xml file enables you to specify properties for each banner advertisement by inserting appropriate elements inside each of the Ad elements. These elements include:
ImageURL
the URL of the image to display for the banner ad
NavigateURL
the web page to which your users will navigate when they click the banner ad
AlternateText
the alternative text to display for browsers that don’t support images
Keyword
the keyword to use to categorize your banner ad
If you use the KeywordFilter property of the AdRotatorcontrol, you can specify the categories of banner ads to display.
Impressions
  the relative frequency with which a particular banner ad should be shown in relation to other banner advertisements
   The higher this number, the more frequently that specific banner will display in the browser. The number provided for this element can be as low as one, but cannot exceed 2,048,000,000; if it does, the page throws an exception.
   Except for ImageURL, all these elements are optional. Also, if you specify an Ad without a NavigateURL, the banner ad will display without a hyperlink.
   To make use of this Ads.xml file, create a new ASP.NET page called AdRotator.aspx, and add the following code to it:

Visual Basic                 LearningASP\VB\AdRotator.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
Using the AdRotator Control
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="adRotator" runat="server"
AdvertisementFile="Ads.xml" />
</div>
</form>
</body>
</html>

Figure : Displaying ads using AdRotator.aspx
  
    As with most of our examples, the C# version of this code is the same except for the Page declaration. You’ll also need to copy the workatdorknozzle.gif and getthenewsletter.gif image files from the code archive and place them in your working folder in order to see these ad images. Save your work and test it in the browser; the display should look something like aboveFigure.
     Refresh the page a few times, and you’ll notice that the first banner appears more often than the second. This occurs because the Impression value for the first Ad is double the value set for the second banner, so it will appear twice as often.

TreeView
     The TreeView control is a very powerful control that’s capable of displaying a complex hierarchical structure of items. Typically, we’d use it to view a directory structure or a site navigation hierarchy, but it could be used to display a family tree, a corporate organizational structure, or any other hierarchical structure.

       The TreeView can pull its data from various sources. We’ll talk more about the various kinds of data sources later in the book; here, we’ll focus on the SiteMapDataSource class, which, as its name suggests, contains a hierarchical sitemap. By default, this sitemap is read from a file called Web.sitemap that’s located in the root of your project (you can easily create this file using the Site Map template in Visual Web Developer). Web.sitemap is an XML file that looks like this:
                                     LearningASP\VB\Web.sitemap
<siteMap
xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode title="Home" url="~/Default.aspx"
description="Home">
<siteMapNode title="SiteMapPath" url="~/SiteMapPath.aspx"
description="TreeView Example" />
<siteMapNode title="TreeView" url="~/TreeViewSitemap.aspx"
description="TreeView Example" />
<siteMapNode title="ClickEvent" url="~/ClickEvent.aspx"
description="ClickEvent Example" />
<siteMapNode title="Loops"
url="~/Loops.aspx"
description="Loops Example" />
</siteMapNode>
</siteMap>

   To use this file, you’ll need to add a SiteMapDataSource control to the page, as well as a TreeView control that uses this data source, like this:

Visual Basic                   LearningASP\VB\TreeViewSiteMap.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.blosums.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.blosums.org/1999/xhtml">
<head runat="server">
<title>
TreeView Demo
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SiteMapDataSource ID="mySiteMapDataSource"
runat="server" />
<asp:TreeView ID="myTreeView" runat="server"
DataSourceID="mySiteMapDataSource" />
</div>
</form>
</body>
</html>
   Note that although the SiteMapDataSource is a control, it doesn’t generate any HTML within the web page. There are many data source controls like this; we’ll delve into them in more detail later.
When combined with the example Web.sitemap file above, this web form would generate an output like that shown in below Figure.
Figure : A simple TreeView control
  
   As you can see, the TreeView control generated the tree for us. The root Home node can even be collapsed or expanded.
In many cases, we won’t want to show the root node; we can hide it from view by setting the ShowStartingNode property of the SiteMapDataSource to false:
<asp:SiteMapDataSource ID="mySiteMapDataSource" runat="server"
ShowStartingNode="false" />

SiteMapPath
     The SiteMapPath control provides the functionality to generate a breadcrumb navigational structure for your site. Breadcrumb systems help to orientate users, giving them an easy way to identify their current location within the site, and providing handy links to the current location’s ancestor nodes. An example of a breadcrumb navigation system is shown in below Figure .

    The SiteMapPath control will automatically use any SiteMapDataSource control that exists in a web form, such as the TreeView control in the previous example, to display a user’s current location within the site. For example, you could simply add the following code to a new web form to achieve the effect shown in below Figure :
Figure 4.8. A breadcrumb created using the SiteMapPath control

Visual Basic                        LearningASP\VB\SiteMapPath.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
SiteMapPath Demo
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SiteMapDataSource ID="mySiteMapDataSource"
runat="server" />
<asp:SiteMapPath ID="mySiteMapPath" runat="server"
DataSourceID="mySiteMapDataSource"
PathSeparator=" > " />
</div>
</form>
</body>
</html>

    Note that the SiteMapPathcontrol allows you to customize the breadcrumbs’ separator
character via the PathSeparator property. Also note that if you don’t have a file named Default.aspx in the directory, the root node link won’t work.

Menu
The Menu control is similar to TreeView in that it displays hierarchical data from a data source; the ways in which we work with both controls are also very similar. The most important differences between the two lie in their appearances, and the fact that Menu supports templates for better customization, and displays only two levels of items (menu items and submenu items).

MultiView
    The MultiView control is similar to Panel in that it doesn’t generate interface elements
itself, but contains other controls. However, a MultiView can store more pages of data (called views), and lets you show one page at a time. You can change the active view (the one that’s being presented to the visitor) by setting the value of the ActiveViewIndex property. The first page corresponds to an ActiveViewIndex of 0; the value of the second page is 1; the value of the third page is 2; and so on.

    The contents of each template are defined inside child Viewelements. Consider the following code example, which creates a Button control and a MultiView control:

Visual Basic                  LearningASP\VB\MultiView.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub SwitchPage(s as Object, e as EventArgs)
myMultiView.ActiveViewIndex = _
(myMultiView.ActiveViewIndex + 1) Mod 2
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
MultiView Demo
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:Button ID="myButton" Text="Switch Page"
runat="server" OnClick="SwitchPage" />
</p>
<asp:MultiView ID="myMultiView" runat="server"
ActiveViewIndex="0">
<asp:View ID="firstView" runat="server">
<p>... contents of the first view ...</p>
</asp:View>
<asp:View ID="secondView" runat="server">
<p>... contents of the second view ...</p>
</asp:View>
</asp:MultiView>
</div>
</form>
</body>
</html>

C#                             LearningASP\CS\MultiView.aspx(excerpt)
<%@ Page Language="C#" %>

<script runat="server">
 public void SwitchPage(Object s, EventArgs e) 

myMultiView.ActiveViewIndex = (myMultiView.ActiveViewIndex + 1) % 2;
 }
 </script> 


   As you can see, by default, the ActiveViewIndex is 0, so when this code is first executed, the MultiView will display its first template, which is shown in below Figure .
   Clicking on the button will cause the second template to be displayed. The SwitchPage event handler uses the modulo operator, Mod in VB and % in C#, to set the ActiveViewIndex to 1 when its original value is 0, and vice versa.
    The MultiView control has a number of other handy features, so be sure to check the documentation for this control if you’re using it in a production environment.
Figure : Using the MultiView control
    Wizard
   The Wizard control is a more advanced version of the MultiView control. It can display one or more pages at a time, but also includes additional built-in functionality such as navigation buttons, and a sidebar that displays the wizard’s steps.

List Controls | ASP.Net Tutorial | ASP.Net Tutorial PDF

   Here, we’ll meet the ASP.NET controls that display simple lists of elements: ListBox, DropDownList, CheckBoxList, RadioButtonList, and BulletedList.

DropDownList
A DropDownListcontrol is similar to the HTML select element. The DropDownList control allows you to select one item from a list using a drop-down menu. Here’s an example of the control’s code:
<asp:DropDownList id="ddlFavColor" runat="server">
<asp:ListItem Text="Red" value="red" />
<asp:ListItem Text="Blue" value="blue" />
<asp:ListItem Text="Green" value="green" />
</asp:DropDownList>

   The most useful event that this control provides is SelectedIndexChanged. This event is also exposed by other list controls, such as the CheckBoxList and RadioButtonList controls, allowing for easy programmatic interaction with the control you’re using. These controls can also be bound to a database and used to extract dynamic content into a drop-down menu.

ListBox
    A ListBox control equates to the HTML select element with either the multiple or size attribute set (size would need to be set to a value of 2 or more). If you set the SelectionMode attribute to Multiple, the user will be able to select more than one item from the list, as in this example:
<asp:ListBox id="listTechnologies" runat="server"
SelectionMode="Multiple">
<asp:ListItem Text="ASP.NET" Value="aspnet" />
<asp:ListItem Text="JSP" Value="jsp" />
<asp:ListItem Text="PHP" Value="php" />
<asp:ListItem Text="CGI" Value="cgi" />
<asp:ListItem Text="ColdFusion" Value="cf" />
</asp:ListBox>

RadioButtonList
      Like the RadioButtoncontrol, the RadioButtonListcontrol represents radio buttons. However, the RadioButtonList control represents a list of radio buttons and uses more compact syntax. Here’s an example:
<asp:RadioButtonList id="favoriteColor" runat="server">
<asp:ListItem Text="Red" Value="red" />
<asp:ListItem Text="Blue" Value="blue" />
<asp:ListItem Text="Green" Value="green" />
</asp:RadioButtonList>

CheckBoxList
As you may have guessed, the CheckBoxList control represents a group of check boxes; it’s equivalent to using several CheckBox controls in a row:
<asp:CheckBoxList id="favoriteFood" runat="server">
<asp:ListItem Text="Pizza" Value="pizza" />
<asp:ListItem Text="Tacos" Value="tacos" />
<asp:ListItem Text="Pasta" Value="pasta" />
</asp:CheckBoxList>

BulletedList
    The BulletedListcontrol displays bulleted or numbered lists, using <ul>(unordered list) or <ol> (ordered list) tags. Unlike the other list controls, the BulletedList doesn’t allow the selection of items, so the SelectedIndexChanged event isn’t supported.

    The first property you’ll want to set is DisplayMode, which can be Text(the default), or HyperLink, which will render the list items as links. When DisplayMode is set to HyperLink, you can use the Click event to respond to a user’s click on one of the items.
       The other important property is BulletStyle, which determines the style of the bullets. The accepted values are:
  • Numbered (1, 2, 3, …)
  • LowerAlpha (a, b, c, …)
  • UpperAlpha (A, B, C, …)
  • LowerRoman (i, ii, iii, …)
  • UpperRoman (I, II, III, …)
  • Circle
  • Disc
  • Square
  • CustomImage
     If the style is set to CustomImage, you’ll also need to set the BulletStyleImageUrl to specify the image to be used for the bullets. If the style is one of the numbered lists, you can also set the FirstBulletNumber property to specify the first number or letter that’s to be generated.

Standard Web Server Controls | ASP.Net Tutorial | ASP.Net Tutorial PDF

    The standard set of web server controls that comes with ASP.NET mirrors the HTML server controls in many ways. However, web server controls offer some new refinements and enhancements, such as support for events and view state, a more consistent set of properties and methods, and more built-in functionality. In this section, we’ll take a look as some of the controls you’re most likely to use in your day-today work.

       Remember to use the .NET Framework SDK Documentation whenever you need more details about any of the framework’s classes (or controls). You can access the documentation from the Help > Index menu item in Visual Web Developer. To find a class, simply search for the class’s name. If there are many classes with a given name in different namespaces, you’ll be able to choose the one you want from the Index Results window. For example, you’ll find that there are two classes named Label, located in the  System.Web.UI.WebControls and System.Windows.Forms namespaces, as below Figure illustrates. You’ll most likely be interested in the version of the class situated in the WebControls namespace.

                  Figure : Documentation for the Label control
 
Label
   The easiest way to display static text on your page is simply to add the text to the body of the page without enclosing it in a tag. However, if you want to modify the text displayed on a page using ASP.NET code, you can display your text within a Label control. Here’s a typical example:

<asp:Label id="messageLabel" Text="" runat="server" />
The following code sets the Text property of the Label control to display the text “Hello World”:

Visual Basic
Public Sub Page_Load()
messageLabel.Text = "Hello World"
End Sub

C#
public void Page_Load()
{
messageLabel.Text = "Hello World";
}

Reading this Page_Load handler code, we can see that when the page first loads, the Text property of the Label control with the id of message will be set to “Hello World.”

Literal
       This is perhaps the simplest control in ASP.NET. If you set Literal’s Text property, it will simply insert that text into the output HTML code without altering it. Unlike Label, which has similar functionality, Literal doesn’t wrap the text in <span> tags that would allow the setting of style information.

TextBox
     The TextBox control is used to create a box in which the user can type or read standard text. You can use the TextMode property to set this control to display text in a single line, across multiple lines, or to hide the text being entered (for instance, in HTML password fields). The following code shows how we might use it in a simple login page:

<p>
Username: <asp:TextBox id="userTextBox" TextMode="SingleLine"
Columns="30" runat="server" />
</p>
<p>
Password: <asp:TextBox id="passwordTextBox"
TextMode="Password" Columns="30" runat="server" />
</p>
<p>
Comments: <asp:TextBox id="commentsTextBox"
TextMode="MultiLine" Columns="30" Rows="10"
runat="server" />
</p>
In each of the instances above, the TextMode attribute dictates the kind of text box that’s to be rendered.

HiddenField
HiddenFieldis a simple control that renders an inputelement whose typeattribute is set to hidden. We can set its only important property, Value.

Button
By default, the Button control renders an input element whose type attribute is set to submit. When a button is clicked, the form containing the button is submitted to the server for processing, and both the Click and Command events are raised.

The following markup displays a Button control and a Label:
<asp:Button id="submitButton" Text="Submit" runat="server" OnClick="WriteText" />
<asp:Label id="messageLabel" runat="server" />

    Notice the OnClick attribute on the control. When the button is clicked, the Click event is raised, and the WriteText subroutine is called. The WriteText subroutine will contain the code that performs the intended function for this button, such as displaying a message to the user:

Visual Basic
Public Sub WriteText(s As Object, e As EventArgs)
messageLabel.Text = "Hello World"
End Sub


C#
public void WriteText(Object s, EventArgs e)
{
messageLabel.Text = "Hello World";
}

     It’s important to realize that events are associated with most web server controls, and the basic techniques involved in using them, are the same events and techniques we used with the Click event of the Button control. All controls implement a standard set of events because they all inherit from the WebControl base class.

ImageButton
An ImageButton control is similar to a Button control, but it uses an image that we supply in place of the typical system button graphic. Take a look at this example:
<asp:ImageButton id="myImgButton" ImageUrl="myButton.gif"
runat="server" OnClick="WriteText" />
<asp:Label id="messageLabel" runat="server" />

The Click event of the ImageButton receives the coordinates of the point at which the image was clicked:
Visual Basic
Public Sub WriteText(s As Object, e As ImageClickEventArgs)
messageLabel.Text = "Coordinate: " & e.X & "," & e.Y
End Sub

C#
public void WriteText(Object s, ImageClickEventArgs e)
{
messageLabel.Text = "Coordinate: " + e.X + "," + e.Y;
}

LinkButton
    A LinkButton control renders a hyperlink that fires the Click event when it’s clicked. From the point of view of ASP.NET code, LinkButtons can be treated in much the same way as buttons, hence the name. Here’s LinkButton in action:
<asp:LinkButton id="myLinkButon" Text="Click Here" runat="server" />

HyperLink
The HyperLink control creates on your page a hyperlink that links to the URL in the NavigateUrl property. Unlike the LinkButton control, which offers features such as Click events and validation, HyperLinks are meant to be used to navigate from one page to the next:

<asp:HyperLink id="myLink" NavigateUrl="http://www.sitepoint.com/"
ImageUrl="splogo.gif" runat="server">SitePoint</asp:HyperLink>

     If it’s specified, the ImageUrl attribute causes the control to display the specified image, in which case the text is demoted to acting as the image’s alternate text.

CheckBox
    You can use a CheckBoxcontrol to represent a choice that can have only two possible states—checked or unchecked:
<asp:CheckBox id="questionCheck" Text="Yep, ASP.NET is cool!" Checked="True" runat="server" />

    The main event associated with a CheckBox is the CheckChanged event, which can be handled with the OnCheckChanged attribute. The Checkedproperty is Trueif the checkbox is checked, and False otherwise.

RadioButton
A RadioButton is a lot like a CheckBox, except that RadioButtons can be grouped to represent a set of options from which only one can be selected. Radio buttons are grouped together using the GroupName property, like so:

<asp:RadioButton id="sanDiego" GroupName="City" Text="San Diego" runat="server" /><br />
<asp:RadioButton id="boston" GroupName="City" Text="Boston" runat="server" /><br />
<asp:RadioButton id="phoenix" GroupName="City" Text="Phoenix" runat="server" /><br />
<asp:RadioButton id="seattle" GroupName="City" Text="Seattle" runat="server" />

     Like the CheckBox control, the main event associated with RadioButtons is the CheckChanged event, which can be handled with the OnCheckChangedattribute. The other control we can use to display radio buttons is RadioButtonList, which we’ll also meet in this chapter.

Image
   An Image control creates an image that can be accessed dynamically from code; it equates to the <img> tag in HTML. Here’s an example:
<asp:Image id="myImage" ImageUrl="mygif.gif" runat="server" AlternateText="description" />

ImageMap
    The ImageMapcontrol generates HTML to display images that have certain clickable regions called hot spots. Each hot spot reacts in a specific way when it’s clicked by the user.
 
    These areas can be defined using three controls, which generate hot spots of different shapes: CircleHotSpot, RectangleHotSpot, and PolygonHotSpot. Here’s an example that defines an image map with two circular hot spots:

Table : Possible values of HotSpotMode
<asp:ImageMap ID="myImageMap" runat="server" ImageUrl="image.jpg">
<asp:CircleHotSpot AlternateText="Button1" Radius="20" X="50" Y="50" />
<asp:CircleHotSpot AlternateText="Button2" Radius="20" X="100" Y="50" />
</asp:ImageMap>

     To configure the action that results when a hot spot is clicked by the user, we set the HotSpotMode property of the ImageMap control, or the HotSpotMode property of the individual hot spot objects, or both, using the values shown in Table 4.2. If the HotSpotMode property is set for the ImageMap control as well as for an individual hot spot, the latter property will override that set for the more general ImageMap control.

      The Microsoft .NET Framework SDK Documentation for the ImageMap class and HotSpotMode enumeration contains detailed examples of the usage of these values.

PlaceHolder
The PlaceHoldercontrol lets us add elements at a particular place on a page at any time, dynamically, through our code. Here’s what it looks like:
<asp:PlaceHolder id="myPlaceHolder" runat="server" />

   The following code dynamically adds a new HtmlButton control within the placeholder:
Visual Basic
Public Sub Page_Load()
Dim myButton As HtmlButton = New HtmlButton()
myButton.InnerText = "My New Button"
myPlaceHolder.Controls.Add(myButton)
End Sub

C#
public void Page_Load()
{
HtmlButton myButton = new HtmlButton();
myButton.InnerText = "My New Button";
myPlaceHolder.Controls.Add(myButton);
}

Panel
    The Panelcontrol functions similarly to the div element in HTML, in that it allows the set of items that resides within the tag to be manipulated as a group. For instance, the Panel could be made visible or hidden by a Button’s Click event:
<asp:Panel id="myPanel" runat="server">
<p>Username: <asp:TextBox id="usernameTextBox" Columns="30" runat="server" /></p>
<p>Password: <asp:TextBox id="passwordTextBox" 
TextMode="Password" Columns="30" runat="server" /></p>
</asp:Panel>
<asp:Button id="hideButton" Text="Hide Panel" OnClick="HidePanel" runat="server" />

    The code above places two TextBox controls within a Panel control. The Button control is outside of the panel. The HidePanel subroutine would then control the Panel’s visibility by setting its Visible property to False:

Visual Basic
Public Sub HidePanel(s As Object, e As EventArgs)
myPanel.Visible = False
End Sub

C#
public void HidePanel(Object s, EventArgs e)
{
myPanel.Visible = false;
}
    
     In this case, when the user clicks the button, the Click event is raised and the HidePanelsubroutine is called, which sets the Visibleproperty of the Panelcontrol to False.

Web Server Controls | ASP.Net Tutorial | ASP.Net Tutorial PDF

Web server controls can be seen as advanced versions of HTML server controls.
Web server controls are those that generate content for you—you’re no longer in control of the HTML being used. While having good knowledge of HTML is useful, it’s not a necessity for those working with web server controls.
     Let’s look at an example. We can use the Label web server control to place simple text inside a web form. To change the Label’s text from within our C# or VB code, we simply set its Text property like so:
Visual Basic
myLabel.Text = "Mickey Mouse"

   Similarly, to add a text box to our form, we use the TextBox web server control. Again, we can read or set its text using the Text property:
C#
username = usernameTextBox.Text;

    Though we’re applying the TextBox control, ASP.NET still uses an input element behind the scenes; however, we no longer have to worry about this detail. With web server controls, you no longer need to worry about translating the needs of your application into elements you can define in HTML—you can let the ASP.NET framework do the worrying for you.

    Unlike HTML server controls, web server controls don’t have a direct, one-to-one correspondence with the HTML elements they generate. For example, we can use either of two web server controls—the DropDownList control, or the ListBox control to generate a select element.

    Web server controls follow the same basic pattern as HTML tags, but the tag name is preceded by asp:, and is capitalized using Pascal Casing. Pascal Casing is a form that capitalizes the first character of each word (such as TextBox). The object IDs are usually named using Camel Casing, where the first letter of each word except the first is capitalized (e.g. usernameTextBox).

Consider the following HTML input element, which creates an input text box:
<input type="text" name="usernameTextBox" size="30" />

The equivalent web server control is the TextBox control, and it looks like this:
<asp:TextBox id="usernameTextBox" runat="server" Columns="30">
</asp:TextBox>

    Remember that, unlike any normal HTML that you might use in your web forms, web server controls are first processed by the ASP.NET engine, where they’re transformed to HTML. A side effect of this approach is that you must be very careful to always include closing tags (the </asp:TextBox>part above). The HTML parsers of most web browsers are forgiving about badly formatted HTML code, but ASP.NET is not. Remember that you can use the shorthand syntax (/>) if nothing appears between your web server control’s opening and closing tags. As such, you could also write this TextBox like so:
<asp:TextBox id="usernameTextBox" runat="server" Columns="30" />

To sum up, the key points to remember when you’re working with web server controls are:
  • Web server controls must be placed within a <form runat="server"> tag to function properly.
  • Web server controls require the runat="server" attribute to function properly.
  • We include web server controls in a form using the asp: prefix.
   There are more web server controls than HTML controls. Some offer advanced features that simply aren’t available using HTML alone, and some generate quite complex HTML code for you. We’ll meet many web server controls as we work through this and future chapters.
     For more information on web server controls, including the properties, methods, and events for each, have a look at Appendix A.

Using the HTML Server Controls | ASP.Net Tutorial | ASP.Net Tutorial PDF

     Nothing explains the theory better than a simple, working example. Let’s create a simple survey form that uses the following HTML server controls:
  • HtmlForm
  • HtmlButton
  • HtmlInputText
  • HtmlSelect
        We’ll begin by creating a new file named Survey.aspx. Create the file in the LearningASP\VB or LearningASP\CS folder you created in Chapter 1. For the purpose of the exercises in this chapter we won’t be using a code-behind file, so don’t check the Place code in a separate file checkbox when you create the form.
     Update the automatically generated file with the following code to create the visual interface for the survey:

Visual Basic                 LearningASP\VB\Survey_01.aspx(excerpt)
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
Using ASP.NET HTML Server Controls
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Take the Survey!</h1>
<!-- Display user name -->
<p>
Name:<br />
<input type="text" id="name" runat="server" />
</p>
<!-- Display email -->
<p>
Email:<br />
<input type="text" id="email" runat="server" />
</p>
<!-- Display technology options -->
<p>
Which server technologies do you use?<br />
<select id="serverModel" runat="server" multiple="true">
<option>ASP.NET</option>
<option>PHP</option>
<option>JSP</option>
<option>CGI</option>
<option>ColdFusion</option>
</select>
</p>
<!-- Display .NET preference options -->
<p>
Do you like .NET so far?<br />
<select id="likeDotNet" runat="server">
<option>Yes</option>
<option>No</option>
</select>
</p>
<!-- Display confirmation button -->
<p>
<button id="confirmButton" OnServerClick="Click"
runat="server">Confirm</button>
</p>
<!-- Confirmation label -->
<p>
<asp:Label id="feedbackLabel" runat="server" />
</p>
</div>
</form>
</body>
</html>
The C# version is identical except for the first line—the page declaration:

C#                                    LearningASP\CS\Survey_01.aspx(excerpt)
<%@ Page Language="C#" %>

     From what we’ve already seen of HTML controls, you should have a good idea of the classes we’ll be working with in this page. All we’ve done is place some HtmlInputTextcontrols, an HtmlButtoncontrol, and an HtmlSelect control inside the obligatory HtmlForm control. We’ve also added a Label control, which we’ll use to give feedback to the user.

      When it’s complete, and you view it in Visual Web Developer’s Design mode, the Survey.aspx web form will resemble Figure 4.1. Note that you can’t execute the form yet, because it’s missing the button’s Clickevent handler that we’ve specified using the OnServerClick attribute on the HtmlButton control.

        Figure : A simple form that uses HTML server controls
  
      When a user clicks on the Confirm button, we’ll display the submitted responses in the browser. In a real application, we’d probably be more likely to save this information to a database, and perhaps show the results as a chart. Whatever the case, the code for the Clickevent handler method below shows how we’d access the propertiesof the HTML controls:

Visual Basic                     LearningASP\VB\Survey_02.aspx (excerpt)
<script runat="server">
Sub Click(ByVal s As Object, ByVal e As EventArgs)
Dim i As Integer
feedbackLabel.Text = "Your name is: " & name.Value & "<br />"
feedbackLabel.Text += "Your email is: " & email.Value & _ "<br />"
feedbackLabel.Text += "You like to work with:<br />"
For i = 0 To serverModel.Items.Count - 1
If serverModel.Items(i).Selected Then
feedbackLabel.Text += " - " & _
serverModel.Items(i).Text & "<br />"
End If
Next i
feedbackLabel.Text += "You like .NET: " & likeDotNet.Value
End Sub
</script>
 
C#                          LearningASP\CS\Survey_02.aspx(excerpt)
<script runat="server">
void Click(Object s, EventArgs e)
{
feedbackLabel.Text = "Your name is: " + name.Value + "<br />";
feedbackLabel.Text += "Your email is: " + email.Value + "<br />";
feedbackLabel.Text += "You like to work with:<br />";
for (int i = 0; i <= serverModel.Items.Count - 1; i++)
{
if (serverModel.Items[i].Selected)
{
feedbackLabel.Text += " - " + serverModel.Items[i].Text + "<br />";
}
}
feedbackLabel.Text += "You like .NET: " + likeDotNet.Value;
}
</script>
 
    As with the examples we’ve seen in previous chapters, we start by placing our VB and C# code inside a server-side script block within the <script> part of the page. Next, we create a new Click event handler that takes the two usual parameters. Finally, we use the Label control to display the user’s responses within the page.
          Figure : Viewing the survey results

    Once you’ve written the code, save your work and test the results in your browser. Enter some information and click the button. To select multiple options in the serverModel option box, hold down Ctrl as you click on your preferences. The information you enter should appear at the bottom of the page when the Confirm button is clicked, as shown in above Figure.

    In conclusion, working with HTML server controls is really simple. All you need to do is assign each control an ID, and add the runat="server" attribute. Then, you can simply access and manipulate the controls using VB or C# code on the server side.