1 / 50

Chapter 14

Chapter 14. Additional Topics in C#. Chapter Objectives - 1. Validate user input in the Validating event handler and display messages using an ErrorProvider component Capture and check an individual keystroke from the user Use code snippets in the editor

vlad
Download Presentation

Chapter 14

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 14 Additional Topics in C#

  2. Chapter Objectives - 1 • Validate user input in the Validating event handler and display messages using an ErrorProvider component • Capture and check an individual keystroke from the user • Use code snippets in the editor • Create a multiple-document project with parent and child forms • Arrange child forms vertically, horizontally, or cascaded

  3. Chapter Objectives - 2 • Add toolbars and status bars to your forms using tool strip and status strip controls • Use calendar controls and date methods • Display a Web page on a Windows form using a WebBrowser control • Use WPF Interoperability to add Windows Presentation Framework controls to a Windows Form • Create a WPF application

  4. Advanced Validation Techniques • Using ErrorProvider components • Similar to Web validation controls • Other useful techniques • Set MaxLength and/or CharacterCasing properties of text boxes • Perform field-level validation using the Validating event of input controls

  5. Using ErrorProvider Components - 1 • An ErrorProvider component causes an error messageto appear next to the fieldin error on the form, rather than messages in messageboxes • If the input value is invalid,a blinking icon displaysnext to the field in errorand displays a messagein a popup, similar to aToolTip

  6. Using ErrorProvider Components - 2 • Generally, one ErrorProvider component can be used to validate all controls on the form • It is added to the Component Tray

  7. Using ErrorProvider Components - 3 • Logic same as for a MessageBox solution • Identify an error • Use the Error Provider SetError method • Pops up the icon • General Form • Examples ErrorProviderObject.SetError(ControlName, MessageString); errorProvider1.SetError(quantityTextBox, "Quantity must be numeric."); errorProvider1.SetError(creditCardTextBox, "Required field.");

  8. The MaxLength andCharacterCasing Properties • Help the user enter correct input data in text boxes • MaxLength property • User unable to enter morecharacters than the maximum • CharacterCasing property • Each character user enters is automatically converted to the case specified • Normal (default) • Upper • Lower Input limited to two characters and converted to uppercase

  9. Field-Level Validation • Instead of validating all controls on a form when the user clicks a button, perform field-level validation • Validating event • CausesValidation property • Error Provider components • Error message appears as soon as the user attempts to leave a field with invalid data

  10. Using the Validating Event andCausesValidation Property - 1 • Validating event is best location for validation code • Use CancelEventArgs argument to cancel the event and return focus to the control being validated • Each control on a form has a CausesValidation property, set to true by default • When the focus passes from one control to the next, the CausesValidation property of the new control determines whether the Validating event occurs for the control just left • Set CausesValidation to false on a control such as Cancel or Exit to give the user a way to bypass the validation

  11. Using the Validating Event andCausesValidation Property - 2 • Set the Cancel property of the e argument to true to cancel the Validating event and keep the focus in the field in error private void nameTextBox_Validating(object sender, CancelEventArgs e) { // Validate for a required entry. // Clear any previous error. errorProvider1.SetError(nameTextBox, ""); // Check for an empty string. if (nameTextBox.Text == String.Empty) { // Cancel the event. e.Cancel = true; errorProvider1.SetError(nameTextBox, "Required Field"); } }

  12. Using the Validating Event andCausesValidation Property - 3 • If a validating event requires an entry in the field that receives focus when the form is first displayed, user will be unable to close the form without making an entry • Set e.Cancel = false in the form’s FormClosing event handler Private void ValidationForm_FormClosing(object sender, FormClosingEventArgs e) { //Do not allow validation to cancel the form’s closing. e.Cancel = false; }

  13. Capturing Keystrokesfrom the User - 1 • Check each keystroke that the user enters in the control's KeyDown, KeyPress, or KeyUp event handler • These events occur in the order listed for most keyboard keys • Keystrokes that ordinarily cause an action to occur, such as the Tab key or Enter key generate only a KeyUp event

  14. Capturing Keystrokesfrom the User - 2 • The e argument of the KeyPress event handler is KeyPressEventArgs • KeyChar property holds the character pressed (as a char data type) • To make comparisons, use methods of the char class • Single characters must be enclosed in single quotes • Handled property can be set to true • Indicates that the keystroke needs no further processing • Effectively "throws away" the keystroke

  15. Using the MaskedText Box for Validation • Set the Mask property of a masked text box to help the user enter data in the correct format • Set the Mask property to one of the predefined masks • Write your own • Easiest way—modify one of the existing masks • Follow the syntax rules of a regular expression • Predefined masks include date, time, phone number, Social Security number, and Zip code formats • If the user enters invalid data for the mask, the character is not accepted

  16. Code Snippets • Small samples of code that show how to accomplish many programming tasks • Right-click in the Code Editor and select Insert Snippet • Snippet categories include • loops, decisions, exception handling, and arrays

  17. Sample Projects • Visual Studio includes many sample projects that you can use to learn new techniques • All editions except the Express Edition • Select Help/Contents • Expand the nodes for Development ToolsandLanguages/Visual Studio/Visual C# to find the Visual C# Samples node • Filter for C# • Walkthroughs in Help are another way to learn • Tutorials that give a step-by-step introduction to many techniques and controls

  18. Multiple Document Interface - 1 • SDI – Single document interface • Each form in the project acts independently from the other forms • MDI – Multiple document interface • A parent form and child forms • Example: MS Word has a parent form (the main window) and child forms (each document window) • Open multiple child windows and maximize, minimize, restore, or close each child window • Always stays within boundaries of parent • Close parent window, all child windows close

  19. Multiple Document Interface - 2 • Rules for MDI • If a parent form closes, all children leave with it • Child form always appears inside the parent’s area • C# allows both MDI and SDI (such as a splash form) in the same project • A Window menu displays a list of open windows • Allows the user to move from one active document to another

  20. Multiple Document Interface - 3

  21. Creating an MDI Project - 1 • At design time designate a form as a parent • IsMdiContainer property = true • Designate child forms at run time • Declare a new variable for the form and instantiate it • Set the child’s MdiParent property to the current (parent) form and show it private void childOneToolStripMenuItem_Click(object sender, EventArgs e) { // Display child one form. ChildForm childOneForm = new ChildForm(); childOneForm.MdiParent = this; childOneForm.Show(); }

  22. Creating an MDI Project - 2 • If multiple child windows are displayed, the title bar of each child should be unique • Accomplish by appending a number to the title bar before displaying the form • Similar to Word's Document1, Document2 ChildForm childOneForm = new ChildForm(); childOneForm.MdiParent = this; childOneCountInteger++; childOneForm.Text = "Child One Document " + childOneCountInteger.ToString(); childOneForm.Show();

  23. Adding a Window Menu • Parent form should include a Window menu • Lists open child windows • Allows the user to switch between windowsand arrange multiple child windows • Set the MenuStrip's MdiWindowListItemproperty to the name of the menu to useas the Window menu • Include a separator bar at the bottomof the Window menu • Separates open window list from othermenu choices

  24. Layout Options • Child windows may be arranged in different layouts • Tiled vertically, tiled horizontally, or cascaded • Layout set in code with LayoutMdi method argument • Use one of three constants – TileHorizontal, TileVertical, or Cascade private void tileHorizontallyToolStripMenuItem_Click(object sender, EventArgs e) { // Arrange the child forms horizontally. LayoutMdi(MdiLayout.TileHorizontal); }

  25. Toolbars • Create by using the ToolStrip control • A container that does not yet contain any objects • Several types of objects can be added • ToolStripButtons • ToolStripLabels • Other objects

  26. Setting Up the Buttons - 1 • Add buttons to a tool strip using the drop-down list of objects • Click on Button • Adds a new ToolStripButton object to the ToolStrip • Set the Name and ToolTipText properties • Name the button • i.e. aboutToolStripButton • Assign an image to the Image property

  27. Setting Up the Buttons - 2 • Set button’s AutoSize property to false to make the image display properly • Change DisplayStyle property to Text and modify Text property to display words on the button • Click Insert Standard Items from the ToolStrips’s smart tag or properties window • New, Open, Save, Print, Cut, Copy, Paste and Help Buttons available with pictures • Must create code for each button (not automatic)

  28. Coding for the ToolStrip Buttons • Can create a new event handler for the button click • Since they are shortcuts for menu items, set ToolStripButton’s Click event to the corresponding menu item’s event-handling method

  29. Status Bars • A status bar generally appears across the bottom of a form • Displays information such as date, time, status of Caps Lock and Num Lock keys or error or informational messages • Add a StatusStrip control to the form • Add ToolStripStatusLabel objects to the StatusStrip • Set properties such as Name and ToolTipText at design or run time • Make labels appear at right end of status bar by setting the StatusStrip’s RightToLeft property to true

  30. Displaying the Date and Time - 1 • Use properties and methods of DateTime structure to retrieve and format current date and time • Now property holds system date and time in numeric format • Can be used for calculations • Format date and/or time for display using methods • ToShortDateString, ToLongDateString, ToShortTimeString, ToLongTimeString • Display does not update automatically • Use a Timer component to update the time

  31. Displaying the Date and Time - 2 • Code to update the time on the status strip • Be sure to set the Enabled and Interval properties of the timer private void timer1_Tick(object sender, EventArgs e) { // Update the time on the status strip. // Interval = 1000 milliseconds (one second). timeToolStripStatusLabel.Text = DateTime.Now.ToLongTimeString(); }

  32. The Calendar Controls - 1 • DateTimePicker and MonthCalendar controls display calendars on a form • DateTimePicker takes less screen space • Displays only day and date unless user drops down the calendar • Value property contains date • Control initially displays current date • User selects a date and the program retrieves the Value property • Assign a Date value to the property

  33. The Calendar Controls - 2 Displays a calendar Displays only the day and date unless the user drops down the calendar. Saves screen space.

  34. Displaying Web Pageson a Windows Form • Add a WebBrowser control to a Windows form • Form resembles a browser window in Internet Explorer or displays any HTML page, online or offline • Must have an active Internet connection to display Web pages in the WebBrowser control

  35. The WebBrowser Control • By default control is set to fill entire form (Dock = Fill) • Can add a ToolStrip control for navigation

  36. Checking for the Enter Key • Test if a keystroke is the Enter key in the KeyUp event • The e argument of the KeyUp event handler is KeyEventArgs • KeyCode property holds the key code of the key • Enter key is 13 • Check for the Enter key with either statement if (e.KeyCode == 13) or if (e.KeyCode == Keys.Enter

  37. XML Data Files • Many advantages over other file formats • Platform-independent, not tied to a specific language or vendor • Text-based, can view and edit file with text-edit tools • Easy to make changes • Uni-code compliant and used internationally

  38. Nodes, Elements, and Attributes • Tags delineate elements of the file • Basic structure is a tree • Root node (a file has only one) • Child nodes (can also contain more child nodes) • Nodes at same level referred to as siblings • Within a node values are assigned to attributes

  39. XML File Terminology

  40. Elements in an XML Document

  41. Writing and Reading an XML File • Write an XML file from a program using an XmlWriter object • Contains many methods • Writes properly formed XML files • Elements and attributes identified by tags

  42. C# Tools for Reading XML Files • Use the Load method of an XDocument to read an XML file • Specify a complete path or a URI for the Filename (default is bin\Debug) • Visual Studio’s type inference determines and assigns a strong data type

  43. Loading an XML File intoan XElement Object • Load an XML file into an XElement object • Root node is first item in an XElement object XElement bookData = XElement.Load(“books.xml”); • An XDocument contains information about the document from the top of the file

  44. Using LINQ to XML to Queryan XElement Object • Use LINQ to XML to retrieve data elements from an XElement or XDocument object • Refer to elements in the XElement object on the In clause of LINQ and in the Select clause • Use orderby for sorting and where for conditions • Use a foreach statement to refer to individual attributes of a query, or manipulate the output

  45. Windows PresentationFoundation (WPF) - 1 • WPF provides ability to create richer user interfaces for multiple platform development • Windows Vista uses WPF to bring better multimedia to the operating system • WPF is available in Visual Studio and Microsoft Expression Studio • Microsoft Silverlight is a scaled-down version of WPF • Rich Web-based interface, works with all leading browsers and on multiple platforms • Able to integrate vector-based graphics, media, text, animation and overlays into the Web interface

  46. Windows PresentationFoundation (WPF) - 2 • Web pages are created in two parts, the interface and the application code • Designer creates the interface • Developer does the programming • Expression blend facilitates creating the two parts • In Visual Studio templates exist for a WPF application and for WPF Browser Applications

  47. Windows PresentationFoundation (WPF) - 3 • WPF user interfaces use XAML (Extensible Application Markup Language) • Much more interactive than traditional HTML • XBAP refers to a XAML Browser Application • Runs in an Internet browser • Technology allows creation of hybrid applications

  48. WPF Interoperability - 1 • Allows use of WPF controls in a Windows Forms application • ElementHost available by default • A container that allows addition of other WPF controls to the Windows Form • Add additional available controls at run time, rather than design time • To use WPF Interoperability, add the ElementHost control to a Windows Form • Add the WPF controls in code • Include a using statement for System.Windows.Controls

  49. WPF Interoperability - 2 • Expander control allows part of a page to show or be hidden • User clicks to expand the control, value of the Content property displays

  50. Writing a WPF Application • IDE layout for a WPF application resembles ASP.NET layout • Document window is split, shows XAML and the design • Collapse the XAML screen • Use the grid container to help with flow layout and to place controls • Grid lines can be set to desired height and width • Many controls have same function and feel as Windows Forms controls • Extra properties available with WPF controls

More Related