Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 57 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
57
Dung lượng
0,94 MB
Nội dung
314 Part II Programming Fundamentals Visual Basic executes the event procedure for the Button2 object. You see a message box that looks like this: 5. Click OK in the message box, type a different Web site in the form’s text box, and then click the Visit Site button. You might want to visit the Microsoft Visual Basic Developer Center site located at http://msdn.microsoft.com/vbasic/ to learn more about Visual Basic. 6. Visit a few more Web sites by using the URL Collection form, and then click the List Recent Sites button. Each time you click List Recent Sites, the MsgBox function expands to show the growing URL history list, as shown here: If you visit more than a few dozen Web sites, you’ll need to replace the MsgBox function with a multiline text box on the form. (Can you fi gure out how to write the code?) 7. When you’re fi nished, click the Close button on the form, and then close your Web browser. Congratulations! You’ve learned how to use the Controls collection and how to process collections by using a For Each Next loop. These skills will be useful whenever you work with collections in the System.Collections namespace. As you become more familiar with classic computer science data structures and algorithms related to list management (stacks, queues, dictionaries, hash tables, and other structured lists), you’ll fi nd that System.Collections provides Visual Studio equivalents to help you manage information in extremely innovative ways. (For a few book ideas related to data structures and algo- rithms, see “General Books About Programming and Computer Science” in the Appendix, “Where to Go for More Information.”) Chapter 12 Working with Collections and the System.Collections Namespace 315 One Step Further: VBA Collections If you decide to write Visual Basic macros for Microsoft Offi ce applications in the future, you’ll fi nd that collections play a big role in the object models of Microsoft Offi ce Word, Microsoft Offi ce Excel, Microsoft Offi ce Access, Microsoft Offi ce PowerPoint, and several other applications that support the Visual Basic for Applications (VBA) programming lan- guage. In Word, for example, all the open documents are stored in the Documents collection, and each paragraph in the current document is stored in the Paragraphs collection. You can manipulate these collections with a For Each Next loop just as you did the collections in the preceding exercises. Offi ce 2003 and the 2007 Microsoft Offi ce system offer a large installa- tion base for solutions based on VBA. Tip As a software developer, you should be aware that not everyone has upgraded to the 2007 Offi ce system yet. In some cases, you’ll need to offer solutions based on VBA for several Offi ce versions, because a typical business or organization will have multiple versions of Offi ce in use. The following sample code comes from a Word VBA macro that uses a For Each Next loop to search each open document in the Documents collection for a fi le named MyLetter.doc. If the fi le is found in the collection, the macro saves the fi le by using the Save method. If the fi le isn’t found in the collection, the macro attempts to open the fi le from the c:\vb08sbs\chap12 folder. Dim aDoc As Document Dim docFound As Boolean Dim docLocation As String docFound = False docLocation = "c:\vb08sbs\chap12\myletter.doc" For Each aDoc In Documents If InStr(1, aDoc.Name, "myletter.doc", 1) Then docFound = True aDoc.Save Exit For End If Next aDoc If docFound = False Then Documents.Open FileName:=docLocation End If The macro begins by declaring three variables. The aDoc object variable represents the current collection element in the For Each Next loop. The docFound Boolean variable assigns a Boolean value of True if the document is found in the Documents collection. The docLocation string variable contains the path of the MyLetter.doc fi le on disk. (This routine assumes that the MyLetter.doc fi le is with your book sample fi les in c:\vb08sbs\chap12.) The For Each Next loop cycles through each document in the Documents collection, searching for the MyLetter fi le. If the fi le is detected by the InStr function (which detects one string in another), the fi le is saved. If the fi le isn’t found, the macro attempts to open it by using the Open method of the Documents object. 316 Part II Programming Fundamentals Also note the Exit For statement, which I use to exit the For Each Next loop when the My Letter fi le has been found and saved. Exit For is a special program statement that you can use to exit a For Next loop or a For Each Next loop when continuing will cause unwanted results. In this example, if the MyLetter.doc fi le is located in the collection, continuing the search is fruitless, and the Exit For statement affords a graceful way to stop the loop as soon as its task is completed. Entering the Word Macro I’ve included this sample Word macro to show you how you can use collections in Visual Basic for Applications, but the source code is designed for Word, not the Visual Studio IDE. If you aren’t working in Word, the Documents collection won’t have any meaning to the compiler. The steps you follow to try the macro depend on the version of Word you are using. If you are using Word 2003, you’ll need to start Word, click the Macros command on the Macro submenu of the Tools menu, create a new name for the macro (I used OpenMyDoc), and then enter the code by using the Visual Basic Editor. If you are using Word 2007, you’ll need to start Word, click the Developer tab, click the Macros command, create a new name for the macro, and then enter the code by using the Visual Basic Editor. (If the Developer tab is not shown, you will need to enable it in the Word Options dialog box.) In the Visual Basic Editor, the completed macro looks like the following illustration. You can run the macro by clicking the Run Sub/UserForm button on the toolbar, just as you would run a program in the Visual Studio IDE. Chapter 12 Working with Collections and the System.Collections Namespace 317 Tip Word macros are generally compatible between versions, although I have sometimes run into problems when upgrading VBA macros or supporting multiple versions of Offi ce. If you are using a different version of Word, you may need to slightly modify the sample code shown here. Chapter 12 Quick Reference To Do this Process objects in a collection Write a For Each Next loop that addresses each member of the collection individually. For example: Dim ctrl As Control For Each ctrl In Controls ctrl.Text = "Click Me!" Next Move objects in the Controls collection from left to right across the screen Modify the Control.Left property of each collection object in a For Each Next loop. For example: Dim ctrl As Control For Each ctrl In Controls ctrl.Left = ctrl.Left + 25 Next Give special treatment to an object in a col- lection Test the Name property of the objects in the collection by using a For Each Next loop. For example: Dim ctrl As Control For Each ctrl In Controls If ctrl.Name <> "btnMoveObjects" Then ctrl.Left = ctrl.Left + 25 End If Next Create a new collec- tion and add mem- bers to it Declare a variable by using the New Collection syntax. Use the Add method to add members. For example: Dim URLsVisited As New Collection() URLsVisited.Add(TextBox1.Text) Use Visual Basic for Applications collections in Word If you are using Word 2003, start the program, click the Macros command on the Macro submenu of the Tools menu, give the macro a name, click Create, and then enter the macro code by using the Visual Basic Editor. If you are using Word 2007, start the program, click the Developer tab, click the Macros command, give the macro a name, click Create, and then enter the macro code by using the Visual Basic Editor. Word exposes many useful collections, including Documents and Paragraphs. T o Do th is 319 Chapter 13 Exploring Text Files and String Processing After completing this chapter, you will be able to: Display a text fi le by using a text box object, the LineInput function, and the StreamReader class. Use the My namespace, a time-saving “speed dial” feature within Visual Studio 2008. Save notes in a text fi le by using the PrintLine function and the SaveFileDialog control. Use string processing techniques to compare, combine, and sort strings. Managing electronic documents is an important function in any modern business, and Microsoft Visual Basic 2008 provides numerous mechanisms for working with different document types and manipulating the information in documents. The most basic docu- ment type is the text fi le, which is made up of non-formatted words and paragraphs, letters, numbers, and a variety of special-purpose characters and symbols. In this chapter, you’ll learn how to work with information stored in text fi les on your system. You’ll learn how to open a text fi le and display its contents in a text box object, and you’ll learn how to create a new text fi le on disk. You’ll also learn more about managing strings in your programs, and you’ll use methods in the Microsoft .NET Framework String and StreamReader classes to combine, sort, and display words, lines, and entire text fi les. Displaying Text Files by Using a Text Box Object The simplest way to display a text fi le in a program is to use a text box object. As you have learned, you can create text box objects in any size. If the contents of the text fi le don’t fi t neatly in the text box, you can also add scroll bars to the text box so that the user can examine the entire fi le. To use the Visual Basic language to load the contents of a text fi le into a text box, you need to use four functions. These functions are described in the following table and are demonstrated in the fi rst exercise in this chapter. As I noted earlier, several of these functions replace older keywords in the Visual Basic language. Function Description FileOpen Opens a text fi le for input or output LineInput Reads a line of input from the text fi le EOF Checks for the end of the text fi le FileClose Closes the text fi le Funct i o n Descr i pt i o n 320 Part II Programming Fundamentals Opening a Text File for Input A text fi le consists of one or more lines of numbers, words, or characters. Text fi les are distinct from document fi les and Web pages, which contain formatting codes, and from executable fi les, which contain instructions for the operating system. Typical text fi les on your system are identi- fi ed by Windows Explorer as “Text Documents” or have the fi le name extension .txt, .ini, .log, or .inf. Because text fi les contain only ordinary, recognizable characters, you can display them easily by using text box objects. By using an OpenFileDialog control to prompt the user for the fi le’s path, you can let the user choose which text fi le to open in a program. This control contains the Filter property, which controls the type of fi les displayed; the ShowDialog method, which displays the Open dialog box; and the FileName property, which returns the path specifi ed by the user. The OpenFileDialog control doesn’t open the fi le; it just gets the path. The FileOpen Function After you get the path from the user, you open the fi le in the program by using the FileOpen function. The abbreviated syntax for the FileOpen function is FileOpen(fi lenumber, pathname, mode) You can fi nd the complete list of arguments in the Visual Studio documentation. These are the most important: fi lenumber is an integer from 1 through 255. pathname is a valid Microsoft Windows path. mode is a keyword indicating how the fi le will be used. (You’ll use the OpenMode.Input and OpenMode.Output modes in this chapter.) The fi le number is associated with the fi le when it’s opened. You then use this fi le number in your code whenever you need to refer to the open fi le. Aside from this association, there’s nothing special about fi le numbers; Visual Basic simply uses them to keep track of the differ- ent fi les you open in your program. A typical FileOpen function using an OpenFileDialog object looks like this: FileOpen(1, OpenFileDialog1.FileName, OpenMode.Input) Here the OpenFileDialog1.FileName property represents the path, OpenMode.Input is the mode, and 1 is the fi le number. Chapter 13 Exploring Text Files and String Processing 321 Tip Text fi les that are opened by using this syntax are called sequential fi les because you must work with their contents in sequential order. In contrast, you can access the information in a database fi le in any order. (You’ll learn more about databases in Chapter 18, “Getting Started with ADO.NET.”) The following exercise demonstrates how you can use an OpenFileDialog control and the FileOpen function to open a text fi le. The exercise also demonstrates how you can use the LineInput and EOF functions to display the contents of a text fi le in a text box and how you can use the FileClose function to close a fi le. (For more information about using controls on the Dialogs tab of the Toolbox to create standard dialog boxes, see Chapter 4, “Working with Menus, Toolbars, and Dialog Boxes.”) Run the Text Browser program 1. Start Microsoft Visual Studio, and open the Text Browser project in the c:\vb08sbs\ chap13\text browser folder. The project opens in the IDE. 2. If the project’s form isn’t visible, display it now. The Text Browser form opens, as shown here: 322 Part II Programming Fundamentals The form contains a large text box object that has scroll bars. It also contains a menu strip object that places Open, Close, and Exit commands on the File menu; an open fi le dialog object; and a label providing operating instructions. I also created the property settings shown in the following table. (Note especially the text box settings.) Object Property Setting txtNote Enabled Multiline Name ScrollBars False True txtNote Both CloseToolStripMenuItem Enabled False lblNote Text Name “Load a text fi le with the Open command.” lblNote Form1 Text “Text Browser” 3. Click the Start Debugging button on the Standard toolbar. The Text Browser program runs. 4. On the Text Browser File menu, click the Open command. The Open dialog box opens. 5. Open the c:\vb08sbs\chap13\text browser folder. The contents of the Text Browser folder are shown here: Ob j ect Propert y Settin g Chapter 13 Exploring Text Files and String Processing 323 6. Double-click the Badbills.txt fi le name. Badbills, a text fi le containing an article written in 1951 in the United States about the dangers of counterfeit money, appears in the text box, as shown here: 7. Use the scroll bars to view the entire document. Memorize number 5. 8. When you’re fi nished, click the Close command on the File menu to close the fi le, and then click the Exit command to quit the program. The program stops, and the IDE returns. Now you’ll take a look at two important event procedures in the program. Examine the Text Browser program code 1. On the Text Browser form File menu, double-click the Open command. The OpenToolStripMenuItem_Click event procedure appears in the Code Editor. 2. Resize the Code Editor to see more of the program code, if necessary. [...]... Cols.SubString(6, 6) 'Middle = "Second" Microsoft Visual Basic 2008 Step by Step Part III Designing the User Interface In this part: Chapter 14, Managing Windows Forms and Controls at Run Time 3 47 Chapter 15, Adding Graphics and Animation Effects 373 Chapter 16, Inheriting Forms and Creating Base Classes 391 Chapter 17, Working with Printers ... boxes (called modal forms in Visual Basic 6) retain the focus until the user clicks OK, clicks Cancel, or otherwise dispatches them To display an existing form as a dialog box in Visual Basic 2008, you open it by using the ShowDialog method If you want to display a form that the user can switch away from, you use the Show method instead of the ShowDialog method In Visual Basic 6, forms that can lose... addition to the Visual Basic commands that open and display text files, there are two additional techniques that you can use to open text files in a Visual Studio program: the StreamReader class and the My namespace Because these techniques use NET Framework objects that are available in all Visual Studio programming languages, I prefer them over the Visual Basic only” functions However, Microsoft has... Before Visual Basic can compare one character with another in a sort, it must convert each character into a number by using a translation table called the ASCII character set (also called the ANSI character set) ASCII is an acronym for American Standard Code for Information Interchange Each of the basic symbols that you can display on your computer has a different ASCII code These codes include the basic. .. and the expression "A" > "B" is false Chapter 13 Exploring Text Files and String Processing 3 37 When comparing two strings that each contain more than one character, Visual Basic begins by comparing the first character in the first string with the first character in the second string and then proceeds character by character through the strings until it finds a difference For example, the strings Mike and... elements is the ability to sort a list of strings The basic concepts in sorting are simple You draw up a list of items to sort, and then compare the items one by one until the list is sorted in ascending or descending alphabetical order Chapter 13 Exploring Text Files and String Processing 333 In Visual Basic, you compare one item with another by using the same relational operators that you use to... output forms, reports, and so on Because Visual Basic treats each form as a separate object, you can think of them as simple building blocks that you can combine to create powerful programs In Part III, you’ll focus again on the user interface, and you’ll learn how to add multiform projects, animation effects, visual inheritance, and printing support to your Visual Basic applications 345 Chapter 14 Managing... & " on the " & "circus!" You can also concatenate and manipulate strings by using methods in the String class of the NET Framework library For example, the String.Concat method allows equivalent string concatenation by using this syntax: Dim Slogan As String Slogan = String.Concat("Bring", " on the ", "circus!") Visual Basic 2008 features two methods for string concatenation and many other stringprocessing... This event procedure adds the current date and time to the text box by linking together, or concatenating, the current date (generated by the My.Computer.Clock object and the LocalTime property), a carriage return (added by the vbCrLf constant), and the Text property You could use a similar technique to add just the current date (by using DateString) or any other information to the text in the text... codes include the basic set of “typewriter” characters (codes 32 through 1 27) and special “control” characters, such as tab, line feed, and carriage return (codes 0 through 31) For example, the lowercase letter “a” corresponds to the ASCII code 97, and the uppercase letter “A” corresponds to the ASCII code 65 As a result, Visual Basic treats these two characters quite differently when sorting or performing . want to visit the Microsoft Visual Basic Developer Center site located at http://msdn .microsoft. com/vbasic/ to learn more about Visual Basic. 6. Visit a few more Web sites by using the URL Collection. object models of Microsoft Offi ce Word, Microsoft Offi ce Excel, Microsoft Offi ce Access, Microsoft Offi ce PowerPoint, and several other applications that support the Visual Basic for Applications. and then enter the code by using the Visual Basic Editor. (If the Developer tab is not shown, you will need to enable it in the Word Options dialog box.) In the Visual Basic Editor, the completed