Ch3 server controls


Published on

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Ch3 server controls

  1. 1.  Types of Server Controls, HTML Server Controls, Web Controls, List Controls, Input Validation Controls, Rich Controls
  2. 2.  ASP.NET server controls are a fundamental part ofthe ASP.NET architecture. Server controls are classes in the .NET Frameworkthat represent visual elements on a web form Some of these classes are relativelystraightforward and map closely to a specific HTMLtag.Other controls are much more ambitiousabstractions that render a more complexrepresentation 2
  3. 3. ASP.NET offers many different server controls.HTML server controls: Classes that wrap the standard HTML elements. Two examples include HtmlAnchor (for the <a>tag) and HtmlSelect (for the <select> tag) Can turn any HTML tag into a server control If there isn’t a direct corresponding class,ASP.NET will simply use the HtmlGenericControlclass. simply add the runat="server" attribute toturn into server control 3
  4. 4. Web controls: Duplicate the functionalities of the basic HTMLelements But have a more consistent and meaningful set ofproperties and methods that make it easier for thedeveloper to declare and access them Some examples are the HyperLink, ListBox, andButton controls. More special types of web controls are alsoavailable. 4
  5. 5. Rich controls: Advanced controls have the ability togenerate a large amount of HTML markupand even client-side JavaScript to create theinterface. Examples include the Calendar, AdRotator,and TreeView controls. 5
  6. 6. Validation controls: Set of controls allows you to easily validate anassociated input control against several standard oruser-defined rules. Can specify that the input can’t be empty, that itmust be a number If validation fails, you can prevent pageprocessing or allow these controls to show inlineerror messages in the page. 6
  7. 7. Data controls Include sophisticated grids and lists that aredesigned to display large amounts of data, withsupport for advanced features such as editing,sorting. Includes the data source controls that allowyou to bind todifferent data sources declaratively, withoutwriting extra code. 7
  8. 8. Navigation controls Designed to display site maps and allow the userto navigate from one page to another.Login controls Support forms authentication, an ASP.NET modelfor authenticating users against a database andtracking their status Can use these controls to get prebuilt,customizable login pages, password recovery, anduser-creation wizards. 8
  9. 9. Web parts controls ASP.NET model for building componentized,highly configurable web portals.ASP.NET AJAX controls Allow you to use Ajax techniques in your webpages without forcing you to write client-side code Ajax-style pages can be more responsive becausethey bypass the regular postback-and-refresh pagecycle. 9
  10. 10. ASP.NET mobile controls Set of controls that resembles the webcontrols but is customized to support mobileclients such as PDAs, smart phones, and so on Renders pages to markup standards such asHTML 3.2 or WML 1.1. 10
  11. 11. All server controls derive from the base Control classin the System.Web.UI namespace. 11
  12. 12. Most commonly used members of the Control class Property DescriptionClientID Identifier of the controlControls Returns the collection of child controlsEnableViewState Returns or sets a Boolean value related to view state of controlID Returns or sets the identifier of the controlPage Returns a reference to the page object that contains the controlParent Returns a reference to the control’s parentVisible Returns or sets a Boolean value indicating whether the control should be Rendered 12
  13. 13.  Defined in the namespace System.Web.UI.HtmlControls 13
  14. 14. HTML server controls on the page is the same as what you usefor normal static HTML tags, with the addition of therunat="server“ attribute. Tag Declaration .NET Class Specific Members<a runat="server"> HtmlAnchor HRef, Target, Title, Name, ServerClick event<button HtmlButton CausesValidation,runat="server"> ValidationGroup, ServerClick event<form HtmlForm Enctype, Method, Target,runat="server"> DefaultButton, DefaultFocus Complete this slide – page 120<img HtmlImage Align, Alt, Border, Height,runat="server"> Src, Width 14
  15. 15. Tag Declaration .NET Class Specific Members<input HtmlInputButton Type, Value,type="button" CausesValidation,runat="server"> ValidationGroup, ServerClick event<input HtmlInputReset Type, Valuetype="reset"runat="server"><input HtmlInputSubmit Type, Value, CausesValidation,type="submit" ValidationGroup, ServerClickrunat="server"> event<input HtmlInputCheckBox Checked, Type, Value,type="checkbox" ServerClick eventrunat="server"> 15
  16. 16. Tag Declaration .NET Class Specific Members<input type="file" HtmlInputFile Accept, MaxLength,runat="server"> PostedFile, Size, Type, Value<input HtmlInputHidden Type, Value,type="hidden" ServerChange eventrunat="server"><input HtmlInputImage Align, Alt, Border,type="image" Src, Type, Value,runat="server"> CausesValidation, ValidationGroup, ServerClick event<input HtmlInputRadioButton Checked, Type, Value,type="radio" ServerChange eventrunat="server"> 16
  17. 17. Tag Declaration .NET Class Specific Members<input type="text" HtmlInputText MaxLength, Type,runat="server"> Value, ServerChange event<input HtmlInputPassword MaxLength, Type,type="password" Value,runat="server"> ServerChange event<select HtmlSelect Multiple,runat="server"> SelectedIndex, Size, Value, DataSource, DataTextField, DataValueField, Items (collection), ServerChange event<table HtmlTable Align, BgColor,runat="server">, Border,<td runat="server"> BorderColor, CellPadding, CellSpacing, Height, 17
  18. 18. Tag Declaration .NET Class Specific Members<th runat="server"> HtmlTableCell Align, BgColor, Border, BorderColor, ColSpan, Height, NoWrap, RowSpan, VAlign, Width<tr runat="server"> HtmlTableRow Align, BgColor, Border, BorderColor, Height, VAlign, Cells (collection)<textarea HtmlTextArea Cols, Rows, Value,runat="server"> ServerChange eventAny other HTML HtmlGenericControl Nonetag with therunat="server" 18
  19. 19.  Can configure a standard HtmlInputTextcontrol To read or set the current text in the textbox, you use the Value property. 19
  20. 20.  Sometimes you don’t know in advance how manytext boxes, radio buttons, table rows, or othercontrols because this might depend on other factors such asthe number of records stored in a database or theuser’s input. With ASP.NET, the solution is easy. Can simply create instances of the HTML servercontrols you need, set their properties with theobject-oriented approach 20
  21. 21.  HTML server controls provide a sparse eventmodel with two possible events: ServerClick andServerChange. The ServerClick event is simply a click that isprocessed on the server side The ServerChange event responds when achange has been made to a text or selectioncontrol 21
  22. 22. HTML Control Events Event Controls That Provide ItServerClick HtmlAnchor, HtmlButton, HtmlInputButton, HtmlInputSubmit,HtmlInputReset, HtmlInputImageServerChange HtmlInputText, HtmlInputCheckBox, HtmlInputRadioButton, HtmlInputHidden, HtmlSelect, HtmlTextArea 22
  23. 23. Portion of the Inheritance Hierarchy for Web Controls 23
  24. 24.  HTML server controls provide a relatively fast wayto migrate to ASP.NET ASP.NET provides a higher-level web controlmodel web controls are defined in theSystem.Web.UI.WebControls namespace Web controls also enable additional features,such as automatic postback Extended controls don’t just map a single HTMLtag but instead generate more complex output madeup of several HTML tags and JavaScript code 24
  25. 25.  All the web controls inherit from the WebControlclass. The WebControl class also derives from Control. 25
  26. 26. Property DescriptionAccessKey Returns or sets the keyboard shortcut that allows the user to quickly navigate to the control.BackColor Returns or sets the background colorBorderColor Returns or sets the border colorBorderStyle One of the values from the BorderStyle enumeration, including Dashed, Dotted, Double, Groove, Ridge, Inset, Outset, Solid, and None. 26
  27. 27. Property DescriptionBorderWidth Returns or sets the border width.CssClass Returns or sets the CSS style to associate with the control. The CSS style can be defined in a <style> section at the top of the page or in a separate CSS file referenced by the page.Enabled Returns or sets the control’s enabled state. If false, the control is usually rendered grayed out and is not usable.Font Returns an object with all the style information of the font used for the control’s text.27
  28. 28. Property DescriptionForeColor Returns or sets the foreground color.Height Returns or sets the control’s height.TabIndex A number that allows you to control the tab order. This property is supported only in Internet Explorer 4.0 and higher.Tooltip Displays a text message when the user hovers the mouse above the control. Many older browsers don’t support this property.Width Returns or sets the control’s width. 28
  29. 29. ASP.NET Generated HTML Key Members<asp:Button> <input type="submit"/> Text, CausesValidation, or PostBackUrl,ValidationG <input type="button"/> roup, Click event<asp:CheckBox> <input AutoPostBack, Checked, type="checkbox"/> Text, TextAlign, CheckedChanged event<asp:FileUpload <input type="file"> FileBytes, FileContent,> FileName, HasFile, PostedFile, SaveAs()<asp:HiddenFiel <input type="hidden"> Valued> 29
  30. 30. ASP.NET Generated HTML Key Members<asp:HyperLink> <a>...</a> ImageUrl, NavigateUrl, Target, Text<asp:Image> <img/> AlternateText, ImageAlign, ImageUrl<asp:ImageButton <input CausesValidation,> type="image"/> ValidationGroup, Click event<asp:ImageMap> <map> HotSpotMode, HotSpots (collection), AlternateText, 30 ImageAlign,
  31. 31. ASP.NET Generated HTML Key Members<asp:Label> <span>...</span> Text, AssociatedControlID<asp:LinkButton> <a><img/></a> Text, CausesValidation, Validation- Group, Click event<asp:Panel> <div>...</div> BackImageUrl, DefaultButton, GroupingText, HorizontalAlign, Scrollbars, Wrap<asp:RadioButton> <input type="radio"/> AutoPostBack, Checked, GroupName, Text, TextAlign, CheckedChanged event 31
  32. 32. ASP.NET Generated HTML Key Members<asp:Table> <table>...</table> BackImageUrl, CellPadding, CellSpacing, GridLines, HorizontalAlign, Rows (collection)<asp:TableCell <td>...</td> ColumnSpan, HorizontalAlign,> RowSpan, Text, VerticalAlign, Wrap<asp:TableRow <tr>...</tr> Cells (collection),> HorizontalAlign, VerticalAlign<asp:TextBox> <input type="text"/> AutoPostBack, Columns, or MaxLength, ReadOnly, Rows, <textarea>...</textar Text, TextMode, Wrap, ea> TextChanged event 32
  33. 33. <asp:TextBox runat="server" ID="TextBox1"Text="This is a test” ForeColor="red"BackColor="lightyellow" Width="250px”Font-Name="Verdana" Font-Bold="True" Font-Size="20" />Differences:• The control is declared using its class name (TextBox)instead of the HTML tag name (input).• The default content is set with the Text property, instead ofa less obvious Value attribute.• The style attributes (colors, width, and font) are set bydirect properties, instead of being grouped together in asingle style attribute. 33
  34. 34. Enumerations: Enumerations are used heavily in the .NET class library Used to group a set of related constants. For example, can set a control’s BorderStyle property, youcan choose one of several predefined values from theBorderStyle enumeration ctrl.BorderStyle = BorderStyle.Dashed;In the .aspx file, set an enumeration by specifying one ofthe allowed values as a string (don’t include the name of theenumeration type) <asp:TextBox BorderStyle="Dashed" Text="Border Test" id="txt” runat="server" /> 34
  35. 35. Colors: Color property refers to a Color object (System.Drawing namespace) Can create Color objects in several ways:• Using an ARGB (alpha, red, green, blue) color value: specify eachvalue as integer. // Create a color from an ARGB value. int alpha = 255, red = 0, green = 255, blue = 0; ctrl.ForeColor = Color.FromArgb(alpha, red, green, blue);• Using a predefined .NET color name: choose the correspondinglynamed read-only property from the Color class // Create a color using a .NET name. ctrl.ForeColor = Color.Blue;• Using an HTML color name: You specify this value as a string usingthe ColorTranslator class. // Create a color from an HTML code. ctrl.ForeColor = ColorTranslator.FromHtml("Blue"); 35
  36. 36. The Default Button: ASP.NET includes a mechanism that allows youto designate a default button on a web page.The default button is the button that is“clicked” when the user presses the Enter key. <form id="Form1" DefaultButton="cmdSubmit" runat="server“> 36
  37. 37. Scrollable Panels: The Panel control has the ability to scroll.The panel is rendered as a <div> tag. 37
  38. 38.  Server-side events work in much the sameway as the server events of the HTML servercontrols. Web controls support the AutoPostBackfeature. Example application adds a new entry to alist control every time one of the eventsoccurs 38
  39. 39.  The list controls are specialized web controlsthat generate list boxes, drop-down lists, and otherrepeating controls. Can be either bound to a data source Allow the user to select one or more items 39
  40. 40. Control Description A drop-down list populated by a collection of<asp:DropDownList <asp:ListItem> objects.In HTML, it is rendered> by a <select> tag with the size="1" attribute. A list box list populated by a collection of<asp:ListBox> <asp:ListItem> objects. In HTML, it is rendered by a <select> tag with the size="x" attribute, where x is the number of visible items.<asp:CheckBoxList> Its items are rendered as check boxes.<asp:RadioButtonLis Like the <asp:CheckBoxList>, but the items aret> rendered as radiobuttons. A static bulleted or numbered list. In HTML, it<asp:BulletedList> is rendered using the <ul> or <ol> tags( Can use to create list of hyperlinks). 40
  41. 41.  The selectable list controls include theDropDownList, ListBox, CheckBoxList, andRadioButtonList controls. RadioButtonList and CheckBoxList rendermultiple option buttons or check Boxes. 41
  42. 42. The BulletedList control is the server-side equivalent of the <ul> (unordered list) or <ol> Property DescriptionBulletStyle Determines the type of listBulletImageUrl If the BulletStyle is set to CustomImage, this points to the image.FirstBulletNumber this sets the first valueDisplayMode Determines whether the text of each item is rendered as text or a hyperlink 42
  43. 43. Validation Control Description<asp:RequiredFieldValid Checks that the control to validate is not empty.ator><asp:RangeValidator> Checks that the value of the associated control is within a specified range<asp:CompareValidator Checks that the value of the associated control> matches a specified comparison<asp:RegularExpression Checks if the value of the control it has toValidator> validate matches the specified regular expression<asp:CustomValidator> Allows you to specify any client-side JavaScript validation routine and its server-side counterpart for validataion<asp:ValidationSummar Shows a summary with the error messages fory> each failed validator on the page 43
  44. 44.  What happens when the user clicks thebutton depends on the value of theCausesValidation property. CausesValidation is false: ASP.NET willignore the validation controls. CausesValidation is true (the default):ASP.NET will automatically validate thepage when the user clicks the button. 44
  45. 45. The validation control classes are found in theSystem.Web.UI.WebControls namespace and inheritfrom the BaseValidator class.BaseValidator Members:ControlToValidate DisplayEnableClientScript EnabledErrorMessage TextIsValid SetFocusOnErrorValidationGroup Validate() 45
  46. 46.  The simplest available control is RequiredFieldValidator. Ensures that the associated control is not empty. Simple Example:<asp:TextBox runat="server" ID="Name" /><asp:RequiredFieldValidator runat="server"ControlToValidate="Name" ErrorMessage="Name isrequired” Display="dynamic">*</asp:RequiredFieldValidator> 46
  47. 47.  The RangeValidator control verifies that an input value fallswithin a predetermined range. The MinimumValue and MaximumValue properties define aninclusive range of valid values Example: <asp:TextBox runat="server" ID="DayOff" /><asp:RangeValidator runat="server" Display="dynamic"ControlToValidate="DayOff" Type="Date"ErrorMessage="Day Off is not within the valid interval"MinimumValue="08/05/2008"MaximumValue="08/20/2008">*</asp:RangeValidator> 47
  48. 48. The CompareValidator control compares a value in one controlwith a fixed value or, more commonly, a value in another control.Operator property allows you to specify the type of comparisonyou want to do(Equal, NotEqual, GreaterThan, GreaterThanEqual,LessThan, LessThanEqual, and DataTypeCheck). The DataTypeCheck value forces the validation control to checkthat the input has the required data type. <asp:TextBox runat="server" ID="Age" /> <asp:CompareValidator runat="server" Display="dynamic" ControlToValidate="Age" ValueToCompare="18" ErrorMessage="You must be at least 18 years old" Type="Integer" Operator="GreaterThanEqual">* </asp:CompareValidator> 48
  49. 49.  The RegularExpressionValidator control is a powerful tool in theASP.NET developer’s toolbox. allows you to validate text by matching against a pattern definedin a regular expressionRegular expressions are also powerful tools—they allow you tospecify complex rules. <asp:TextBox runat="server" ID="Email" /> <asp:RegularExpressionValidator runat="server" ControlToValidate="Email" ValidationExpression=".*@.{2,}..{2,}" ErrorMessage="E-mail is not in a valid format" Display="dynamic">* </asp:RegularExpressionValidator> 49
  50. 50. Character DescriptionEscapesOrdinary Characters other than .$^{[(|)*+? matchcharacters themselvesb Matches a backspacet Matches a tabr Matches a carriage returnv Matches a vertical tab.f Matches a form feedn Matches a newline If followed by a special character (one of .$^{[(|)*+?), this character escape matches that character literal. 50
  51. 51. Character Class Description. Matches any character except n.[aeiou] Matches any single character specified in the set.[^aeiou] Matches any character not specified in the set.[3-7a-dA-D] Matches any character specified in the specified ranges (in the example the ranges are 3–7, a–d, A–D).w Matches any word character; that is, any alphanumeric character or the underscore (_).W Matches any non-word characters Matches any whitespace character (space, tab, form feed, newline, carriage return, or vertical feed).S Matches any non-whitespace character.d Matches any decimal character.D Matches any non-decimal character 51
  52. 52. QuantifiersQuantifier Quantifier Description* Zero or more matches+ One or more matches? Zero or one matches{N} N matches{N,} N or more matches{N,M} Between N and M matches (inclusive 52
  53. 53. Commonly Used Regular ExpressionsContent Regular Expression DescriptionE-mail address S+@S+.S+ Defines an email address that requires anat symbol (@) and a dot (.), and only allows nonwhitespace characters.Password w+ Defines a password that allows any sequence of word charactersSpecific-length w{4,10} Defines a password that must be atpassword leastfour characters long but no longer than ten CharactersAdvanced [a-zA-Z]w{3,9} Defines a password that allowspassword four to ten total characters, as with the specific-length password. The twist is that the first character must fall in the range of a–z or A–Z (that is to say, it must start with a nonaccented ordinary 53 letter).
  54. 54. Commonly Used Regular ExpressionsContent Regular Expression DescriptionAnother [a-zA-Z]w*d+w* Defines a password that starts withadvanced a letter character, followed bypassword zero or more word characters, one or more digits, and then zero or more word characters. In short, it forces a password to contain a number somewhere inside it. You could use a similar pattern to require two numbers or any other special character.Limited-length S{4,10} Defines a string of four to tenfield characters (like the password example), but it allows special characters (asterisks, ampersands, 54 and so on).
  55. 55. Commonly Used Regular ExpressionsContent Regular Expression DescriptionSocial Security d{3}-d{2}-d{4} Defines a sequence of three, two,number (US) and then four digits, with each group separated by a hyphen. A similar pattern could be used when requiring a phone number. 55
  56. 56.  The ValidationSummary control doesn’tperform any validation it allows you to show a summary of all theerrors in the page summary displays the ErrorMessage value ofeach failed validator ShowMessageBox and ShowSummaryProperties 56
  57. 57.  Rich controls provide an object model that has a complex HTML representation and also client side JavaScript.Examples:- AdRotator Calendar
  58. 58.  Steps for using AdRotator Define the XML schedule file with <Ad> tag and its properties defined Specify Advertisement file value un AdRotator definition in Page design view. AdCreated event can be trapped
  59. 59. TAG Description<ImageUrl> The image that will be displayed.<NavigateUrl> The link will be followed if user clicks the banner.<Alternate> The text will be displayed in place of picture. A new ad is selected whenever the Web<Impression> page refreshes. An impression attribute can be assigned to each ad. It controls how often an ad is selected relative to other ad in ad file
  60. 60.  <asp:Calendar ID="Calendar2" runat="server"></asp:Calendar>