1 / 54

Advanced Windows Forms Controls and Coding

Advanced Windows Forms Controls and Coding Objectives Describe and create a Windows Forms application with a Windows Explorer- or Microsoft Outlook-style user interface Understand the use of the TreeView, ListView, Splitter, and Panel Windows Forms controls

lotus
Télécharger la présentation

Advanced Windows Forms Controls and Coding

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. Advanced Windows Forms Controls and Coding

  2. Objectives • Describe and create a Windows Forms application with a Windows Explorer- or Microsoft Outlook-style user interface • Understand the use of the TreeView, ListView, Splitter, and Panel Windows Forms controls • Understand how user controls are created, compiled, and incorporated into projects

  3. Windows Explorer- and Outlook-style Applications • Categories of user interfaces in Visual Basic .NET Windows Forms applications • Single document interface (SDI) • Multiple document interface (MDI) • Explorer-style interface • Windows Explorer-style interface uses two principal controls • TreeView • ListView control • Microsoft Outlook-style interface uses the following principal controls • TreeView • ListView control • Panel control

  4. Understanding the TreeView Control • TreeView Control • Displays a list of items called nodes • Every node in the tree can have lower-level nodes, called child nodes, attached to it • Node that has a child is referred to as a parent node • Important properties of a TreeView control • Nodes • SelectedNode

  5. Understanding the TreeView Control (Continued) • Populating the tree view at design time • Can add nodes to a TreeView control by opening the TreeNode Editor • Populating the tree view at runtime • Can add a new root node by instantiating a new TreeNode object, and then invoking the Add method of the control’s Nodes collection to add that new node instance to the collection • Traversing All Nodes of a TreeView Control – Recursion • Recursive method • A method that calls itself

  6. The Factorial Console Application

  7. Understanding the ListView Control • ListView control • Displays a list of items and, optionally, an icon next to each item • Items appear in one of four views (based on the View property) • LargeIcon, SmallIcon, List, or Details • Items collection • Main property of ListView control • Items can be added in the Windows Form Designer or in code • Add button adds a ListViewItem • Text is assigned in the ListViewItem’s Text property

  8. Populating a ListView Control • Can be done by inserting ListViewItem objects in code • At runtime • Identifying and manipulating selected ListViewItem(s) is also accomplished in code • The following code adds an item named My new list view item with an ImageIndex of 2: • ListView1.Items.Add(“My new List view item”, 2) • Within the IDE • Column headers for the ListView control are specified in the ColumnHeader Collection Editor • Within the ListViewItem Collection Editor • Clicking the SubItems Collection property opens the ListViewSubItem Collection Editor

  9. Understanding the Splitter Control • Splitter control • Permits the user to resize docked controls at runtime • Typical application is to allow the user to move the boundary between a TreeView control and a ListView control

  10. Understanding the Panel Control • With additional Splitter controls • You can divide the form into smaller and smaller resizable areas • Make sure to include a container control to hold the Splitter and the two docked controls • Panel control • Similar to the GroupBox control • Automatically displays scroll bars when the size of the graphical content exceeds the Panel control’s display area • Does not have a caption

  11. Understanding User Controls (Windows Forms) • User control • A control you have defined and created • Visual Basic .NET supports Windows Forms user controls that inherit from • An existing Windows Forms control • The UserControl class • A previously defined user control • The Control class

  12. User Controls Based on an Existing Windows Forms Control • Simplest form of user control • Requires you to modify a Windows Forms control already in the Toolbox to extend its functionality in some way • Can be useful if an existing Toolbox control already provides most, but not all, of the functionality you need

  13. Property Declaration Example, with a Private Variable

  14. User Control Based on the UserControl Class • UserControl class • Provides a container for several controls that you select from the Windows Forms Toolbox • Is a template for a component class that includes a graphical interface • Controls based on this class exhibit • Properties such as Location, Size, BackColor, Enabled, and Visible • Methods such as BringToFront, GetType, Dispose, GetNextControl, and Hide • Events such as Click, DoubleClick, MouseDown, Enter, and Leave

  15. User Controls Based on the Control Class • The Control class • Provides most of the standard properties, events, and methods of all controls • Provides much of the internal structure needed to operate in its environment • A handle for Windows to keep track of it • Message routing • Mouse and keyboard events • Visual display properties such as BackColor and Visible • User-triggered events such as Click and DoubleClick • Does not include the instructions for painting a graphical control • Developer is responsible for rendering the graphical image of the Control

  16. Populating the Tree View at Runtime • To populate a TreeView control at runtime: • In the Code Editor, delete the statement in the Form1_Load event procedure that adds a ListViewItem (you deal with the ListView control later, but doing this now cleans up the screen for the present demos) • Insert the code shown in Figure 5-24 into the Form1_Load event procedure • Run the Sample Windows Explorer style form application. Expand all of the categories • Quit the application and return to the IDE

  17. Adding Tree View Nodes at Runtime

  18. Traversing All Nodes of a TreeView Control • To process all nodes of the demo TreeView control: • In the Nodes Collection for TreeView1, insert additional nodes under the Senior node as shown in Figure 5-26. To do this, click the Nodes Collection property to open the TreeNode Editor. In the TreeNode Editor, click Senior |Add Child, and type Internationally Ranked as the label. Add the remaining nodes shown in Figure 5-26 in the same way • Place a Button control on top of the ListView control. Change its Text property to Iterate all nodes and its Name property to btnIterate • Double-click btnIterate, and insert the btnIterate_Click() procedure shown in Figure 5-27 • Also insert the new ChangeText() procedure, as shown in Figure 5-28 • Run the Sample Windows Explorer style form application. Expand all of the nodes. Click the Iterate all nodes button

  19. TreeNode Editor, with Added Nodes

  20. btnIterate_Click()

  21. ChangeText() Procedure

  22. Populating and Manipulating the ListView Control • To display items in the ListView control: • Change the View property of ListView1 to List • Assign ImageList1 to the SmallImageList property of ListView1 • Insert the following statement into the TreeView1_AfterSelect() procedure: ListView1.Items.Add(e.Node.Text, e.Node.ImageIndex) • Run the Sample Windows Explorer style form application • Close the application to return to the IDE, and close the solution

  23. Creating the Microsoft Outlook-style Graphical Component • To create the Microsoft Outlook-style GUI: • In Visual Studio .NET, start a new Windows application project. Call the project Sample Microsoft Outlook style form. Put this in the VB.NET\Student\Tut05 folder • Enlarge Form1 to a width of 600 pixels and a height of 400 pixels. Set the form’s Text property to Sample Microsoft Outlook style form • Place a TreeView control on the form. Set its Dock property to Left and its Width property to 200. Click the ellipsis next to Nodes Collection property, and add root nodes called France, Netherlands, and Great Britain. Under the Netherlands root node, add child nodes for Heidi Gielgud and Hans Van Peldt. Add an ImageList control to the form, and load the three flag icons into it (found at VS7\Common7\Graphics\icons\Flags\). Then assign ImageList1 to the ImageList property of the TreeView control. Return to the tree view Nodes collection, and assign the appropriate flag icon to the Image property for each node • In the Toolbox, double-click the Splitter control

  24. Creating the Microsoft Outlook-style Graphical Component (Continued) • Now add a Panel control to the form. Place it in the right half, and set its Dock property to Fill • Drop a ListView control onto the Panel control, and set its Dock property to Top. In the Items Collection property, add ListView items with the titles of several events for female sprinters: 100 Meter Dash, 100 Meter Hurdles, and 200 Meter Dash • Add another Splitter control along the bottom edge of the ListView control, and set its Dock property to Top • Drag a PictureBox control into the lower-right quadrant of the form, and set its Dock property to Fill. Set its Image property to the icon representing the flag of the Netherlands, and set the SizeMode property to StretchImage • Run the Sample Microsoft Outlook style form application

  25. Creating the ctrlTxtSingleNum Enhanced TextBox Control • To create the ctrlTxtSingleNum user control: • Start a new Visual Basic .NET Windows application. Put it in the VB.NET\Student\Tut05 folder. Name the project NumbersOnlyPlease • Click Project | Add User Control. In the Add New Item – NumbersOnlyPlease dialog box, User Control is already selected. Name this control ctrlTxtSingleNum.vb, and then click Open • In Solution Explorer, select the code window for ctrlTxtSingleNum.vb. Right after the Public Class ctrlTxtSingleNum declaration, change the Inherits statement to Inherits System.Windows.Forms.TextBox • To set some initial properties for this control, expand the Windows Form Designer generated code, and insert these two lines following InitializeComponent() on line 10: • Me.BackColor = Color.LightBlue • Me.Width = 50

  26. Creating the ctrlTxtSingleNum Enhanced TextBox Control (Continued) • In order to validate the data entered by the user in the enhanced text box, you program the Leave event • Now insert the code shown in Figure 5-32 into the ctrlTxtSingleNum_Leave() event procedure • To make the new control available in the Toolbox, you must save the file containing the user control and build (that is, compile) the project • Run the NumbersOnlyPlease application. Test the new control by inputting numeric and nonnumeric data. Close the application

  27. Adding a Property to Develop the ctrlTxtSingleNum Control • Property declarations require Get and Set statements • Get statement retrieves value of the property from the private variable • Set statement stores the property setting in the private variable • At design time and at runtime • Get executes when you want to look up the value of the PositiveNumRequired property • Set executes whenever you assign True or False to that property

  28. Converting ctrlTxtSingleNum into a Windows Control Library • To convert ctrlTxtSingleNum into a Windows Control Library: • Start a new Visual Basic .NET project. Choose Windows Control Library as the project type. Name the project ctrlSingleNumLib, and save it in the VB.NET\Student\Tut05 folder. In Solution Explorer, change the name of the .vb file from UserControl1.vb to ctrlSingleNum.vb • You are now going to copy the code from ctrlTxtSingleNum.vb into ctrlSingleNum.vb • Click Build | Build Solution, because the .dll file must exist before you can test the control • In Solution Explorer, right-click the solution name, point to Add, then click New Project. Make this a Windows Application project type, name it TestSingleNum, and store it under the ctrlSingleNumLib folder. In Solution Explorer, right-click the TestSingleNum project name, and select Set as StartUp Project

  29. Converting ctrlTxtSingleNum into a Windows Control Library (Continued) • In Solution Explorer, right-click References under TestSingleNum, and add a reference to the ctrlSingleNum project. In the Add Reference dialog box, click the Projects tab, select ctrlSingleNum, and then click OK • Right-click the Toolbox, and select Customize Toolbox. In the Customize Toolbox dialog box, click the .NET Framework Components tab. Then click Browse, and locate the ctrlSingleNum.dll file. Click OK • As before, drag three ctrlSingleNum controls from the Toolbox onto the form, toggle the PositiveNumRequired property on one of them, and test the ctrlSingleNumLib application

  30. Inheriting from the UserControl Class • To create ctrlReceipt: • Start a new Windows Control Library project. Place it in the VB.NET\ Student\Tut05 folder, and name it ctrlReceipt. Change the project filename to ctrlReceipt.vb. In the Code Editor, change the class name to ctrlReceipt.vb • Open the User Control Designer. Build the GUI so that it appears as shown in Figure 5-35 • Use the private single variable sngTaxRate along with the public property TaxRate to allow the user to change the default sales tax rate of five percent. Following the model you used in developing ctrlTxtSingleNum, declare Private sngTaxRate As Single = .05 • Then declare a public property called TaxRate, along with the Get and Set statements that copy the value of sngTaxRate to TaxRate, and from TaxRate to sngTaxRate, respectively. Enter the following statement: Public Property TaxRate As Single

  31. Inheriting from the UserControl Class (Continued) • Write the btnCompute_Click() procedure to perform the necessary calculations • Click Save All, and then build the solution. Once again, you need a client project to test the ctrlReceipt user control. Add a new Windows application project to the ctrlReceipt solution, called TestCtrlReceipt, and set this as the startup project • Open Form1 of TestCtrlReceipt in the Windows Form Designer, if necessary. Drag a ctrlReceipt user control from the Toolbox onto Form1 • Run the TestCtrlReceipt application using the default five percent sales tax rate and inputting the amount 7.99

  32. Inheriting from Another User Control • To create the ctrlFocReceipt user control: • In Solution Explorer, right-click the solution name, and add another Windows Control Library project to this solution. Name the new project ctrlFocReceiptLib • In Solution Explorer for the new project, name the control ctrlFocReceipt and its file ctrlFocReceipt.vb • Insert the code shown in Figure 5-39 that declares the properties (Purpose and TaxRate) and associated private variables • Click Save All, and build the project • To test the new control, add a Windows application to the current solution, called TestCtrlFocReceipt, and remember to set this as the startup project • Run the TestCtrlFocReceipt application, inputting 100 for Amount

  33. Property Declarations for ctrlFocReceipt

  34. Planning a Draft of the Scoring Application • Events.txt and Associated Code • Contains all the events for the Friendsville International Games • Copy this file into an array when the main form loads • User Controls • ctrlNation • Used for identifying the competing nations in team sports competitions • Also identifies the country affiliation of athletes in individual competitions • ctrlTeamScore • Used in the Team Scoring module • Individual Scoring – Speed • Provides for the display of the names and country affiliations of two to eight competitors

  35. Creating a Draft of the Scoring Application • To initiate the main project: • Click File | New | Blank Solution. Name this solution Scoring (Draft), and place it in the VB.NET\Student\Tut05 folder • In Solution Explorer, right-click Scoring (Draft), and add a new Windows application project called Scoring, located under the Scoring (Draft) folder. Rightclick Scoring and set it as the startup project. Change the name of Form1 to frmScoreMain, and the filename to frmScoreMain.vb. Click Scoring, and open the Property pages for the project. Set the Startup object to frmScoreMain • Design the GUI. Place a TreeView control on the left (with its Dock property set to Left), a Splitter control next to it, and a ListView control on the right (with its Dock property set to Fill). Change the form’s Text property to Competition Scoring – Main Form. In the Properties window for TreeView1, click the Nodes Collection to open the TreeNode Editor. In the TreeNode Editor, add three Root nodes (Sports, Venues, and Schedule), and then add the child nodes under each of these

  36. Creating a Draft of the Scoring Application (Continued) • Add an ImageList control. Place a closed folder icon and an open folder icon in the ImageList’s Images Collection. Back in the TreeView control, assign ImageList1 to the ImageList property. Then assign the index value for the closed folder (0) to the ImageIndex property, and the index value for the open folder (1) to the SelectedImageIndex property • In the ListView control, set the View property to Details. Then, in the Columns property, click the ellipsis after (Collection) to open the ColumnHeader Collection Editor. In the ColumnHeader Collection Editor, enter five column headers, with name, text, and width properties • Click Save All. Test the Scoring application

  37. Assembling Prewritten Elements • To add Hilda’s record layout and files to the Scoring application: • In Solution Explorer, click the project name Scoring. Then click Project | Add Module. Click Open to open the Code Editor for Module1.vb • Click File | Open | File to open the file Hilda.txt, found in the VB.NET\Student\Tut05 folder and shown in Figure 5-43, and copy its contents into Module1.vb. Close Hilda.txt. Save Module1.vb • Open Events.txt, and note that the record layout you saw in Figure 5-43 matches the data in Events.txt • Two of the elements in Module1.vb are coded: ScoringMethod and VenueIndex. Each of these employs a small array to decode the element. Insert the array declarations for the pastrScoringMethods() array shown in Figure 5-45 and the pastrVenues() array shown in Figure 5-46 at the end of Module1 before the End Module statement

  38. Assembling Prewritten Elements (Continued) • A simple loop is all that you need to load Events.txt into the array at the time the application starts up. Open the Code Editor for frmScoreMain.vb if necessary, and insert the frmScoreMain_Load() procedure shown in Figure 5-47 • The executable program is created in the bin folder, and the executable must find and open the data files used in the application. For this reason, copy the data file Hilda created, Events.txt, into the Tut05\Scoring (Draft)\Scoring\ bin folder • Click Build | Build Solution to ensure that you have made no syntax errors

  39. Building a Control Library and Adding It to an Application • ctrlNation • Depends on the existence of the Nations.txt text • Contains three Windows Forms controls • Combo box • Label • ImageIndex • Nations.txt • Contains one record for each country participating in the Friendsville International Games • Each record contains • The three-character internationally adopted country abbreviation (USA, FRA, etc.) • The name of the country • An index value indicating the position of this country’s flag in the collection of images loaded into an ImageIndex control

  40. ctrlNation’s Code

  41. How to Create the ctrlNationLib Control • To add the ctrlNationLib control library to the Scoring (Draft) application • Copy the ctrlNation folder from the VB.NET\Student\Tut05 folder to the Scoring (Draft) folder • In Solution Explorer, right-click Scoring (Draft) (the solution name), and click Add | Existing Project. In the Add Existing Project dialog box, navigate to the ctrlNation folder that you just copied into Scoring (Draft), and click ctrlNationLib to add the control library project to the solution • In Solution Explorer, under the Scoring project, right-click References, and click Add Reference. In the Add Reference dialog box, click the Projects tab, and browse to the ctrlNation folder in the Scoring (Draft) folder. Select the ctrlNationLib project, and click OK. Then build the solution. Open the Toolbox, and note the presence of the ctrlNation control at the end of the list of Windows Forms controls

  42. How to Create the ctrlTeamScoreLib Control • To add the ctrlTeamScoreLib control library to the Scoring (Draft) application: • Copy the TeamScoring folder from the VB.NET\Student\Tut05 folder to the Scoring (Draft) folder • In Solution Explorer, right-click the solution name Scoring, click Add | Existing Project, navigate to the TeamScoring folder that you just copied into Scoring (Draft), and click ctrlTeamScoreLib to add the control library to the solution • In Solution Explorer, under the Scoring project, right-click References. Add a reference to the ctrlTeamScoreLib project • Compile the solution (by clicking Build | Build Solution). Note that ctrlTeamScore now appears in the Toolbox

  43. How to Create the ctrlEventHeader Control • To add the ctrlEventHeaderLib control library to the Scoring (Draft) application: • Copy the ctrlEventHeader folder from the VB.NET\Student\Tut05 folder to the Scoring (Draft) folder • In Solution Explorer, right-click the solution name, and click Add | Existing Project. Navigate to the ctrlEventHeader folder that you just copied into Scoring (Draft), and click ctrlEventHeaderLib to add the control library to the solution • In Solution Explorer, under the Scoring project, right-click References. Add a reference to the ctrlEventHeaderLib project • Compile the solution (by clicking Build | Build Solution). Note that ctrlEventHeader now appears in the Toolbox

  44. Adding frmSpeed, the First Competition Scoring Module • To add frmSpeed to the Scoring (Draft) application: • Copy the file frmSpeed.vb from the Tut05 folder to the VB.NET\Student\ Tut05\Scoring (Draft)\Scoring folder • In Solution Explorer, right-click the Scoring project, and click Add | Add Existing Item, and select frmSpeed.vb • Click Build | Build Solution to ensure that you have not introduced any syntax errors

  45. Completing a Draft of the Scoring Application • To populate ListView1 • In the Code Editor for frmScoreMain, insert the code in Figure 5-61 • Complete the Case “Schedule” section, modeling your code on the code in the other two cases shown • At the bottom of the procedure, if ItemCtr is zero (that is, no elements have been added to the ListView control), add the message No events scheduled yet to ListView1 • Also insert the AddListViewItem() procedure shown in Figure 5-62. Note the code that adds the .Sport SubItem on line 5. Complete this procedure by adding lines 6 through 8 for the missing subitems (gender, venue, and schedule) • Run the Scoring (draft) application to ensure that the list view is populated as it should be. Click a node in the tree view, and note the items that appear in the list view. Then run the original Scoring application provided to you, click the same tree view node, and see that the list view contains the same items

  46. TreeView1_AfterSelect() procedure (incomplete)

  47. AddListViewItem() Procedure (incomplete)

  48. Creating frmTeam • To add frmTeam to the Scoring (Draft) application: • In Solution Explorer, right-click the Scoring project, and click Add | Add Windows Form. Name the new form frmTeam, and its file as frmTeam.vb • Set the form’s Text property to Team Scoring, and enlarge the form as needed • From the Toolbox, drop a ctrlEventHeader control onto the top half of the form • From the Toolbox, drop a ctrlTeamScore control onto the bottom half of the form • In the Code Editor of frmTeam, insert the SetHeaderInfo procedure. Copy this procedure from frmSpeed, as shown in Figure 5-57

  49. Creating Stubs for frmDistance and frmJudge • To add stubs for the competition scoring modules • Right-click the Scoring project name in Solution Explorer. Click Add | Add Windows Form. Name the new form frmDistance, and its file frmDistance.vb • Drop a ctrlEventHeader control onto the top half of the form • Insert a label control in the bottom half of the form, with the message This module is under construction • Copy the SetHeaderInfo procedure from frmSpeed into the Code Editor for frmDistance • Repeat Steps 1 through 4 to create and establish the header information for frmJudge • Run the Scoring (draft) application to ensure that no syntax errors have been introduced

  50. Displaying the Competition Scoring Module • To display the competition scoring module: • Program the ListView1_DoubleClick() procedure in frmScoreMain, as shown in Figure 5-63 • The first case shown in Figure 5-63 (with TS for team score) has been written for you. Complete the other cases (S for speed, D for distance, and J for judging), modeled on the TS case • Run the Scoring application

More Related