C++/CLI Essentials Student Guide Revision 1.0 Object Innovations Course 431
C++/CLI Essentials Rev. 1.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Copyright 2006 Object Innovations All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America. Rev. 1.0 Copyright 2006 Object Innovations ii
Table of Contents (Overview) Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Appendix A.NET: What You Need to Know C++/CLI Fundamentals Object-Oriented Programming in C++/CLI C++/CLI and the.net Framework Delegates and Events Introduction to Windows Forms Learning Resources Rev. 1.0 Copyright 2006 Object Innovations iii
Directory Structure The course software installs to the root directory c:\oic\cppess. Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories. The CaseStudy directory contains a case study in multiple steps. The Demos directory is provided for performing in-class demonstrations led by the instructor. Rev. 1.0 Copyright 2006 Object Innovations iv
Table of Contents (Detailed) Chapter 1.NET: What You Need to Know... 1 Getting Started... 3.NET: What Is Really Happening... 4.NET Programming in a Nutshell... 5.NET Program Example... 6 Viewing the Assembly... 7 Viewing Intermediate Language... 8 Understanding.NET... 9 Visual Studio 2005... 10 Visual C++ 2005 Express Edition... 11 Creating a Console Application... 12 Solution Explorer... 13 Adding a C++ File... 14 Using the Visual Studio Text Editor... 15 IntelliSense... 16 Build and Run the Project... 17 Pausing the Output... 18 Visual C++ 2005 and GUI Programs... 19.NET Documentation... 20 Summary... 21 Chapter 2 C++/CLI Fundamentals... 23 Hello, World... 25 Compiling, Running (Command Line)... 26 Program Structure... 27 Namespaces... 29 Variables... 30 Input in C++/CLI... 31 Classes in C++/CLI... 32 InputWrapper Class... 33 Sample Program... 34 Input Wrapper Implementation... 35 Control Structures... 36 C++/CLI Operators... 37 Types in C++/CLI... 38 Simple Types... 39 Types in System Namespace... 40 Implicit Conversions... 41 Explicit Conversions... 42 Cast Notation... 43 value struct... 44 Uninitialized Variables... 45 Enumeration Types... 46 Rev. 1.0 Copyright 2006 Object Innovations v
Enumeration Example... 47 Reference Types... 48 Class Types... 49 Object... 50 String... 51 Copying Strings... 52 StringBuilder Class... 53 Classes and Value Classes... 55 RHotel Ref Class... 56 Copy Constructors in C++/CLI... 57 VHotel Value Class... 58 Test Program... 59 RaisePrice Methods... 60 Value Class versus Ref Class... 61 Arrays... 62 One-Dimensional Arrays... 63 System.Array... 64 Jagged Arrays... 65 Rectangular Arrays... 66 for each for Arrays... 67 Boxing and Unboxing... 68 Output in C++/CLI... 69 Formatting... 70 Formatting Example... 71 Exceptions... 72 Exceptions Sample Program... 73 System::Exception... 75 Lab 2... 76 Summary... 77 Chapter 3 Object-Oriented Programming in C++/CLI... 81 Classic C++ Object Model... 83 Object Lifetime in Classic Model... 84 Object Lifetime in.net Model... 85 Object Lifetime in C++/CLI... 86 Stack Allocation... 87 C++/CLI Object-Oriented Features... 88 Encapsulation and Properties... 89 Using a Property... 90 Indexed Properties... 91 Using an Indexed Property... 92 Trivial Properties... 93 Bank Example... 94 Account Class... 95 Namespace... 97 Constructors... 98 Static Members... 99 Rev. 1.0 Copyright 2006 Object Innovations vi
Inheritance in C++/CLI... 100 New Version of Base Class... 101 Features of the New Base Class... 102 Derived Class... 103 Overriding a Virtual Function... 104 Fragile Base Class Problem... 105 Abstract Ref Classes... 106 Derived Classes... 107 Test Program... 108 Lab 3... 109 Summary... 110 Chapter 4 C++/CLI and the.net Framework... 113 Components and OO in C++/CLI... 115 Interfaces in C++/CLI... 117 Interface Inheritance... 118 Programming with Interfaces... 119 Implementing Interfaces... 120 Using an Interface... 122 Dynamic Interfaces... 123 Account Interfaces... 124 BasicAccount Class... 125 Account Class... 126 Interfaces in C++/CLI and COM... 128 Resolving Ambiguity... 129 Explicit Interface Implementation... 130 Explicit Interfaces Test Program... 131 System::Object... 132 Collections... 134 ArrayList... 135 ArrayList Methods... 136 Example: StringList... 137 Adding and Removing String... 138 IEnumerable and IEnumerator... 139 Using Enumerators... 140 Collections of User-Defined Objects... 141 Account Class... 142 AccountList Class... 144 Copy Semantics in C++/CLI... 147 Deep Copy and ICloneable... 148 Lab 4A... 149 Writing Generic Code... 150 Using a Class of Object... 151 Generic Types... 152 Generic Syntax in C++/CLI... 153 Generic Example... 154 Generic Client Code... 155 Rev. 1.0 Copyright 2006 Object Innovations vii
System::Collections::Generic... 156 Lab 4B... 157 Summary... 158 Chapter 5 Delegates and Events... 163 Overview of Delegates and Events... 165 Callbacks and Delegates... 166 Usage of Delegates... 167 Declaring a Delegate... 168 Defining a Method... 169 Creating a Delegate Object... 170 Calling a Delegate... 171 Random Number Generation... 172 A Random Array... 173 Combining Delegate Objects... 174 Account.h... 175 DelegateAccount.cpp... 176 Events... 177 Events in C++/CLI and.net... 178 Client Side Event Code... 180 Chat Room Example... 181 Lab 5... 182 Summary... 183 Chapter 6 Introduction to Windows Forms... 185 Creating a Windows Forms App... 187 Windows Forms Event Handling... 191 Add Events for a Control... 192 Events Documentation... 193 Closing a Form... 194 ListBox Control... 195 ListBox Example... 196 Lab 6... 197 Summary... 198 Appendix A Learning Resources... 203 Rev. 1.0 Copyright 2006 Object Innovations viii
CppEss Chapter 1 Chapter 1.NET: What You Need to Know Rev. 1.0 Copyright 2006 Object Innovations 1
CppEss Chapter 1.NET: What You Need to Know Objectives After completing this unit you will be able to: Describe the essentials of creating and running a program in the.net environment. Build and run a simple C++/CLI program. Use the ILDASM tool to view intermediate language. Use Visual Studio 2005 or Visual C++ 2005 Express Edition as an effective environment for creating C++/CLI programs. Use the.net Framework SDK documentation. Rev. 1.0 Copyright 2006 Object Innovations 2
CppEss Chapter 1 Getting Started From a programmer s perspective, a beautiful thing about.net is that you scarcely need to know anything about it to start writing programs for the.net environment. You write a program in a high-level language (such as C++/CLI), a compiler creates an executable.exe file (called an assembly), and you run that.exe file. Even very simple programs, if they are designed to do something interesting, such as perform output, will require that the program employ the services of library code. A large library, called the.net Framework Class Library, comes with.net, and you can use all of the services of this library in your programs. Rev. 1.0 Copyright 2006 Object Innovations 3
CppEss Chapter 1.NET: What Is Really Happening The assembly that is created does not contain executable code, but, rather, code in Intermediate Language, or IL (sometimes called Microsoft Intermediate Language, or MSIL). In the Windows environment, this IL code is packaged up in a standard portable executable (PE) file format, so you will see the familiar.exe extension (or, if you are building a component, the.dll extension). You can view an assembly using the ILDASM tool. When you run the.exe, a special runtime environment (the Common Language Runtime, or CLR) is launched and the IL instructions are executed by the CLR. Unlike some runtimes, where the IL would be interpreted each time it is executed, the CLR comes with a just-in-time (JIT) compiler, which translates the IL to native machine code the first time it is encountered. On subsequent calls, the code segment runs as native code. Rev. 1.0 Copyright 2006 Object Innovations 4
CppEss Chapter 1.NET Programming in a Nutshell 1. Write your program in a high-level.net language, such as C++/CLI. 2. Compile your program into IL. 3. Run your IL program, which will launch the CLR to execute your IL, using its JIT to translate your program to native code as it executes. We will look at a simple example of a C++/CLI program, and run it under.net. Don t worry about the syntax of C++/CLI, which we will start discussing in the next chapter. Rev. 1.0 Copyright 2006 Object Innovations 5
CppEss Chapter 1.NET Program Example See SimpleCalc in the Chap01 folder. 1. Enter the program in a text editor. // SimpleCalc.cpp // // This program does a simple calculation: // calculate area of a rectangle int main() { int width = 20; int height = 5; int area; area = width * height; System::Console::WriteLine("area = {0}", area); return 0; } 2. Compile the program at the command-line (start the console window via Start All Programs Microsoft Visual Studio 2005 Visual Studio Tools Visual Studio 2005 Command Prompt). >cl SimpleCalc.cpp /clr:safe 3. Run your IL program SimpleCalc.exe >SimpleCalc area = 100 If you are using Visual C++ 2005 Express Edition, see the note on page 11 about using command-line tools. Rev. 1.0 Copyright 2006 Object Innovations 6
CppEss Chapter 1 Viewing the Assembly You can view the assembly using the ILDASM tool. >ildasm simplecalc.exe Rev. 1.0 Copyright 2006 Object Innovations 7
CppEss Chapter 1 Viewing Intermediate Language Double-click on main : int32() Rev. 1.0 Copyright 2006 Object Innovations 8
CppEss Chapter 1 Understanding.NET The nice thing about a high-level programming language is that you usually do not need to be concerned with the platform on which the program executes. You can work with the abstractions provided by the language and with functions provided by libraries. Your appreciation of the C++/CLI programming language and its potential for creating great applications will be richer if you have a general understanding of.net. After this course, we suggest you next study: 432.NET Framework Using C++/CLI Rev. 1.0 Copyright 2006 Object Innovations 9
CppEss Chapter 1 Visual Studio 2005 While it is possible to write C++/CLI programs using any text editor, and compile them with the commandline compiler, it is very tedious to program that way. An IDE makes the process of writing software much easier. An IDE provides convenience items, such as a syntaxhighlighting editor. An IDE reduces the tedium of keeping track of configurations, environment settings and file organizations. You may use Visual Studio 2005 throughout this course to create and compile your C++/CLI programs. Rev. 1.0 Copyright 2006 Object Innovations 10
CppEss Chapter 1 Visual C++ 2005 Express Edition Microsoft has made available free versions of its Visual Studio 2005 developer tools. Download Visual C++ 2005 Express Edition from: http://msdn.microsoft.com/vstudio/express/visualc/ If you want to use command-line tools, you will need to manually place a couple of directories in your Path variable. The compiler cl.exe is in this folder on the drive where Windows is installed, with the proper version of.net specified: \WINDOWS\Microsoft.NET\Framework\v2.0.50727 The tool ildasm.exe is in this folder on the drive where Visual C++ 2005 Express Edition is installed: \Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin You can edit the Path environment variable from the Advanced tab of the System applet in the Control Panel. Rev. 1.0 Copyright 2006 Object Innovations 11
CppEss Chapter 1 Creating a Console Application We will now create a simple console application. Our program is the same simple calculator we created earlier that was compiled at the command line. 1. From the Visual Studio 2005 main menu, choose File New Project... This will bring up the New Project dialog. 2. Browse to the folder C:\OIC\CppEss\Demos. 3. For Project types, choose CLR under Visual C++. 4. For Templates, choose CLR Empty Project. 5. In the Name field, type SimpleCalcVs. Click OK. Rev. 1.0 Copyright 2006 Object Innovations 12
CppEss Chapter 1 Solution Explorer Notice Solution Explorer in the top-right. You have a solution with a single project. The project has no files yet. Rev. 1.0 Copyright 2006 Object Innovations 13
CppEss Chapter 1 Adding a C++ File At this point, you will have an empty C++ project. We are now going to add a file, SimpleCalc.cpp, which contains the text of our program. 1. In Solution Explorer, right click over SimpleCalcVs and choose Add New Item... This will bring up the Add New Item dialog. 2. For Categories choose Code. 3. For Templates, choose C++ File (.cpp). 4. For Name, type SimpleCalc. Click Add. Visual Studio will append the.cpp extension. You will now see SimpleCalc.cpp shown in Solution Explorer under the Source Files folder. Rev. 1.0 Copyright 2006 Object Innovations 14
CppEss Chapter 1 Using the Visual Studio Text Editor In Solution Explorer, double-click on SimpleCalc.cpp. Enter the following program into the empty file in the Visual Studio text editor. Or you could just copy from Chap01\SimpleCalc\. // SimpleCalc.cpp // // This program does a simple calculation: // calculate area of a rectangle int main() { int width = 20; int height = 5; int area; area = width * height; System::Console::WriteLine("area = {0}", area); return 0; } Notice that the Visual Studio text editor highlights syntax, indents automatically, and so on. Rev. 1.0 Copyright 2006 Object Innovations 15
CppEss Chapter 1 IntelliSense A powerful feature of Visual Studio is IntelliSense. IntelliSense will automatically pop up a list box allowing you to easily insert language elements directly into your code. Rev. 1.0 Copyright 2006 Object Innovations 16
CppEss Chapter 1 Build and Run the Project Building a project means compiling the individual source files and linking them together with any library files to create an IL executable.exe file. You can build the project by using one of the following: Menu Build Build Solution Toolbar Keyboard shortcut Ctrl + Shift + B. You can run the program without the debugger by using one of the following: Menu Debug Start Without Debugging Toolbar (This toolbar button is not provided by default; see Supplement1.pdf for how to add it to your build toolbar.) Keyboard shortcut Ctrl + F5 You can run the program in the debugger by using one of the following: Menu Debug Start Debugging Toolbar Keyboard shortcut F5 Try it! Rev. 1.0 Copyright 2006 Object Innovations 17
CppEss Chapter 1 Pausing the Output If you run the program in the debugger from Visual Studio, you will notice that the output window automatically closes on program termination. To keep the window open, you may prompt the user for some input. int main() { int width = 20; int height = 5; int area; area = width * height; System::Console::WriteLine("area = {0}", area); System::Console::WriteLine( "Prese Enter to exit"); System::Console::ReadLine(); return 0; } This version of the program is saved as a Visual Studio 2005 project in Chap01\SimpleCalcVs. Remember that you can always make the console window stay open by running without the debugger via Control + F5. Rev. 1.0 Copyright 2006 Object Innovations 18
CppEss Chapter 1 Visual C++ 2005 and GUI Programs Microsoft s implementation of the C++/CLI language, Visual C++ 2005, works very effectively in a GUI environment. Using Windows Forms, it is easy to create Windows GUI programs in C++/CLI. Example: See Chap01\SimpleCalcGui We will discuss GUI programming using C++/CLI in Chapter 6. Rev. 1.0 Copyright 2006 Object Innovations 19
CppEss Chapter 1.NET Documentation.NET Framework documentation is included with Visual Studio 2005. Use the menu Help Contents. Rev. 1.0 Copyright 2006 Object Innovations 20
CppEss Chapter 1 Summary As in other environments, with.net you write a program in a high-level language, compile to an executable (.EXE file), and run that.exe file. The.EXE file, called an assembly, contains Intermediate Language instructions. You can view an assembly through the ILDASM tool. Visual Studio 2005 is a powerful IDE that makes it easy to develop C++/CLI programs. A free version, Visual C++ 2005 Express Edition, can be downloaded from Microsoft s Web site. With Visual Studio 2005, it is easy to create GUI programs using C++/CLI. You can access extensive.net Framework documentation through the Visual Studio help system. Rev. 1.0 Copyright 2006 Object Innovations 21
CppEss Chapter 1 Rev. 1.0 Copyright 2006 Object Innovations 22
CppEss Chapter 6 Chapter 6 Introduction to Windows Forms Rev. 1.0 Copyright 2006 Object Innovations 185
CppEss Chapter 6 Introduction to Windows Forms Objectives After completing this unit you will be able to: Use Visual Studio 2005 to implement a simple graphical user interface with Windows Forms and basic controls. Explain the principles of event handling in Windows Forms and implement handlers for simple control events. Use a ListBox control to display a list of objects. Rev. 1.0 Copyright 2006 Object Innovations 186
CppEss Chapter 6 Creating a Windows Forms App It is easy to create a Windows Forms application using the Form Designer in Visual Studio 2005 or Visual C++ 2005 Express Edition. This same Form Designer is available to all.net languages. We ll illustrate the use of Visual Studio 2005. 1. Create a new Visual C++ CLR project BankGui with template Windows Forms Application. 2. Browse to the Demos directory. Do not create a separate directory for the solution. Click OK. Rev. 1.0 Copyright 2006 Object Innovations 187
CppEss Chapter 6 Windows Forms Demo (Cont d) 3. From the toolbox, drag two labels, two textboxes, and two buttons to the form. Use the resizing handles to resize the form. 4. Enter property values for the form, textboxes and buttons: Name Form1 txtamount txtbalance cmddeposit cmdwithdraw Text Bank Account (blank) (blank) Deposit Withdraw 5. Add event handlers for the buttons by double-clicking on each button. 6. Add an event handler for the Form s Load event by doubleclicking over any empty area of the form. Rev. 1.0 Copyright 2006 Object Innovations 188
CppEss Chapter 6 Windows Forms Demo (Cont d) 7. Add the following code: private: System::Void cmddeposit_click( System::Object^ sender, System::EventArgs^ e) { int amount = Convert::ToInt32(txtAmount->Text); int balance = Convert::ToInt32(txtBalance->Text); balance += amount; txtbalance->text = Convert::ToString(balance); } private: System::Void cmdwithdraw_click( System::Object^ sender, System::EventArgs^ e) { int amount = Convert::ToInt32(txtAmount->Text); int balance = Convert::ToInt32(txtBalance->Text); balance -= amount; txtbalance->text = Convert::ToString(balance); } private: System::Void Form1_Load( System::Object^ sender, System::EventArgs^ e) { txtamount->text = "25"; txtbalance->text = "100"; } Rev. 1.0 Copyright 2006 Object Innovations 189
CppEss Chapter 6 Windows Forms Demo (Cont d) 8. Build and run the application. It should behave like a standard Windows application. The completed demo is in the BankGui\Step1 directory for this chapter. Rev. 1.0 Copyright 2006 Object Innovations 190
CppEss Chapter 6 Windows Forms Event Handling GUI applications are event-driven, in which the application executes code in response to user events, such as clicking the mouse, choosing a menu item, etc. Each form or control has a predefined set of events. For example, every button has a Load event. Windows Forms uses the.net event model, which uses delegates to bind events to the methods that handle them. Windows Forms typically uses multi-cast delegates. A multi-cast delegate maintains a list of the methods it is bound to. When an event occurs in an application, the control raises the event by calling the delegate for that event. The delegate then calls all of the methods it is bound to. C++/CLI provides the overloaded += operator for adding a delegate to an event. this->cmddeposit->click += gcnew System::EventHandler(this, &Form1::cmdDeposit_Click); This code is generated by the Form Designer and is in the file Form1.h. Rev. 1.0 Copyright 2006 Object Innovations 191
CppEss Chapter 6 Add Events for a Control Every control has a primary event. You can add a handler for this event by double-clicking on the control in the Visual Studio 2005 Form Designer. We added a handler for the Deposit and Withdraw buttons in this way. You can add other events by selecting the in the Properties window and double-clicking on a selected event. Rev. 1.0 Copyright 2006 Object Innovations 192
CppEss Chapter 6 Events Documentation You can find all of the events associated with a class in the.net Framework Reference. This screen shot shows documentation for the FormClosing event of the Form class. Rev. 1.0 Copyright 2006 Object Innovations 193
CppEss Chapter 6 Closing a Form A form may be closed in a number of ways, such as by clicking the at the top-right, using the system menu at the top-left, pressing Alt+F4, and so on. In all cases, the FormClosing event will be fired, providing an opportunity to cancel the closing. Continuing our simple Bank Account form demo, add the following code to the handler of the FormClosing event. See BankGui\Step2. private: System::Void Form1_FormClosing( System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e) { MessageBox::Show("Form is about to close", "Bank Account"); } The following dialog will be displayed: If you wanted to prevent closing the form, you could set the Cancel property of the FormClosingEventArgs object to true. Rev. 1.0 Copyright 2006 Object Innovations 194
CppEss Chapter 6 ListBox Control The.NET Framework provides a number of controls that you can use to display lists of items to the user. These controls also allow the user to select an item from the list, typically by clicking on the item to be selected. The simplest list control is the ListBox control. The collection Items maintains a collection of object references. There are methods such as Add, Remove and Clear. The property SelectedItem gets or sets the currently selected item in the listbox. Perform a cast to get out an item of a particular type. The property SelectedIndex gets or sets the zero-based index of the currently selected item ( 1 if no item is selected). The event SelectedIndexChanged is fired when the user selects a new index. There are many more properties, methods, and events, which you can study from the documentation. Rev. 1.0 Copyright 2006 Object Innovations 195
CppEss Chapter 6 ListBox Example The program ListBoxDemo illustrates maintaining a list of strings in a listbox. private: System::Void cmdadd_click( System::Object^ sender, System::EventArgs^ e) { listbox1->items->add(txtstring->text); } private: System::Void cmdremove_click( System::Object^ sender, System::EventArgs^ e) { listbox1->items->remove(txtstring->text); } private: System::Void listbox1_selectedindexchanged( System::Object^ sender, System::EventArgs^ e) { if (listbox1->selectedindex!= -1) txtstring->text = (String^)listBox1->SelectedItem; } Rev. 1.0 Copyright 2006 Object Innovations 196
CppEss Chapter 6 Lab 6 A GUI for Acme In this lab, you will implement a GUI interface for the Acme customer management system implemented in the previous chapter. Detailed instructions are contained in the Lab 6 write-up at the end of the chapter. Suggested time: 60 minutes Rev. 1.0 Copyright 2006 Object Innovations 197
CppEss Chapter 6 Summary With Visual Studio 2005, you can implement a simple graphical user interface with Windows Forms and basic controls. Windows Forms uses the.net event architecture to handle user interface events..net provides various list controls, such as ListBox, for displaying lists of objects. Rev. 1.0 Copyright 2006 Object Innovations 198
CppEss Chapter 6 Introduction Lab 6 A GUI for Acme In this lab, you will implement a GUI interface for the Acme customer management system implemented in the previous chapter. Suggested Time: 60 minutes Root Directory: OIC\CppEss Directories: Labs\Lab6\AcmeGui CaseStudy\Acme\Step2C CaseStudy\Acme\Step3 (do your work here) (previous version) (answer) Files: Form1.h Part A. Create the GUI and List Customers 1. Create a new Visual C++/CLI project of type Windows Forms Application AcmeGui located in Labs\Lab6. 2. Change the Text property of the form to Acme Customer Management System. 3. Add controls to the form as shown: 4. Make the names of the controls shown: txtid, txtemailaddress, txtfirstname, txtlastname, listcustomers, cmdregister, cmdunregister, cmdchangeemail. Rev. 1.0 Copyright 2006 Object Innovations 199
CppEss Chapter 6 5. Copy the files Customer.h and Test.cpp from CaseStudy\Acme\Step2C to the working directory. Add the file Customer.h to the project. (Test.cpp will be a miscellaneous file that you can refer to as you migrate command-line client code to GUI client code.) 6. Add to Form1.h an include of Customer.h. Build your project to make sure you get a clean build 7. Add a private data member custs of type Customers^ to class Form1. 8. Create a handler for the Load event in the Form1 class. Add code to instantiate a custs object. 9. From the file Test.cpp, copy code into the Load event handler to display the customer list by calling a helper method ShowCustomerArray(), passing it the results of calling the GetCustomer() method. 10. Implement a private method ShowCustomerArray() to display the customers in the array list in the list box of the main form. Base your code on the code in Test.cs. Don t worry about padding to make neat columns, because it won t work anyway in a listbox with a variable pitch font. (To make neat columns you should use a more advanced control, such as ListView or DataGridView.) Just use a single space as a separator of fields when you build up a string to add to the listbox. To add a string to a listbox, you can use the following code: listcustomers->items->add(str); If the array list is nullptr, throw an exception. 11. Build and test the program. You should see a starting list of customers displayed. Part B. Register a New Customer In this part, you will add code for registering a new customer. 1. Add an event handler for clicking the Register button. 2. Add code in this handler to call the RegisterCustomer method of the Customers class. You will pass in the first name, last name, and email address from the textboxes. You will get back an ID, which you will display. 3. Add code to redisplay all of the customers in the listbox. Build and test. 4. You will see the new customer that was added, but you will also see a duplicate of the original customers. Fix this problem by clearing the listbox in the helper method before doing the display. Build and test. Rev. 1.0 Copyright 2006 Object Innovations 200
CppEss Chapter 6 Part C. Select a Customer and Split into Fields In this part, you will add code to select a customer by clicking in the listbox. Relying on the specification that there are no embedded spaces in any of the fields of a customer, you will extract the individual fields using a space as a separator. This extracted information will be shown in the textboxes. 1. Add a handler for the event SelectedIndexChanged of the listbox. (Recall that you use the button to obtain a list of events associated with a control.) 2. Test to see if an item has been selected by checking if listcustomers.selectedindex is different from 1. 3. If an item has been selected, obtain the selected string and split it into fields (relying on a space as a separator) by the following code: String^ selected = (String^)listCustomers->SelectedItem; array<wchar_t>^ sep = gcnew array<wchar_t> { ' ' }; array<string^>^ fields; fields = selected->split(sep); 5. Add code to set the textboxes to the corresponding fields of the selected customer. 6. Build and test. As you select different customers, you should see the information in the textboxes change appropriately. Part D. Unregister a Customer and Change Email Address In this final part, you will add code for unregistering a new customer. You will also add code for changing an email address. 1. Add a handler for the Unregister button. 2. Add code to unregister the currently selected customer (if there is one), as shown by the ID. When done, clear the textboxes and refresh the listbox. You may build and test at this point. 3. Add a handler for the Change Email button. Add code to change the email address of the currently selected customer (if there is one). 4. Build and test. Your miniature customer management system should now be fully operational! You are now at Step 3. Rev. 1.0 Copyright 2006 Object Innovations 201
CppEss Chapter 6 Rev. 1.0 Copyright 2006 Object Innovations 202