Beginning Microsoft Visual Basic 2008 phần 3 doc

92 331 1
Beginning Microsoft Visual Basic 2008 phần 3 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 5: Working with Data Structures 151 3. Here’s the problem: The user doesn’t know what 2 means. Close the project and find the following section of code at the end of the Hour property: ‘Set the display text lblState.Text = “At “ & value & “:00, Richard is “ & _ CurrentState End Set 4. Change the last line to read as follows: ‘Set the display text lblState.Text = “At “ & value & “:00, Richard is “ & _ CurrentState.ToString End Set 5. Now run the project and you’ll see something like Figure 5-9. Figure 5-9 How It Works As you typed the code, you might have noticed that whenever you tried to set a value against CurrentState, you were presented with an enumerated list of possibilities as shown in Figure 5-10. Figure 5-10 Visual Studio 2008 knows that CurrentState is of type DayAction. It also knows that DayAction is an enumeration and that it defines eight possible values, each of which is displayed in the IntelliSense pop-up box. Clicking an item in the enumerated list causes a tooltip to be displayed with the actual value of the item; for example, clicking DayAction.RelaxingWithFriends will display a tooltip with a value of 6. c05.indd 151c05.indd 151 4/2/08 5:31:50 PM4/2/08 5:31:50 PM Chapter 5: Working with Data Structures 152 Fundamentally, however, because DayAction is based on an integer, CurrentState is an integer value. That’s why, the first time you ran the project with the state determination code in place, you saw an integer at the end of the status string. At 7 A.M., you know that Richard is traveling to work, or rather CurrentState equals DayAction.TravelingToWork. You defined this as 2, which is why 2 is displayed at the end of the string. What you’ve done in this Try It Out is to tack a call to the ToString method onto the end of the CurrentState variable. This results in a string representation of DayAction being used, rather than the integer representation Enumerations are incredibly useful when you want to store one of a possible set of values in a variable. As you start to drill into more complex objects in the Framework, you’ll find that they are used all over the place! Setting Invalid Values One of the limitations of enumerations is that it is possible to store a value that technically isn’t one of the possible defined values of the enumeration. For example, you can change the Hour property so that rather than setting CurrentState to Asleep, you can set it to 999: ElseIf value >= 22 And value < 23 Then CurrentState = DayAction.GettingReadyForBed Else CurrentState = 999 End If If you build the project, you’ll notice that Visual Basic 2008 doesn’t flag this as an error if you have the Option Strict option turned off. When you run the project, you’ll see that the value for CurrentState is shown on the form as 999. So, you can see that you can set a variable that references an enumeration to a value that is not defined in that enumeration and the application will still “work” (as long as the value is of the same type as the enumeration). If you build classes that use enumerations, you have to rely on the consumer of that class being well behaved. One technique to solve this problem would be to disallow invalid values in any properties that used the enumeration as their data type. c05.indd 152c05.indd 152 4/2/08 5:31:50 PM4/2/08 5:31:50 PM Chapter 5: Working with Data Structures 153 Understanding Constants Another good programming practice that you need to look at is the constant. Imagine you have these two methods, each of which does something with a given file on the computer’s disk. (Obviously, we’re omitting the code here that actually manipulates the file.) Public Sub DoSomething() ‘What’s the filename? Dim strFileName As String = “c:\Temp\Demo.txt” ‘Open the file End Sub Public Sub DoSomethingElse() ‘What’s the filename? Dim strFileName As String = “c:\Temp\Demo.txt” ‘Do something with the file End Sub Using Constants The code defining a string literal gives the name of a file twice. This is poor programming practice because if both methods are supposed to access the same file, and if that file name changes, this change has to be made in two separate places. In this instance, both methods are next to each other and the program itself is small. However, imagine you had a massive program in which a separate string literal pointing to the file is defined in 10, 50, or even 1,000 places. If you needed to change the file name, you’d have to change it many times. This is exactly the kind of thing that leads to serious problems for maintaining software code. What you need to do instead is define the file name globally and then use that global symbol for the file name in the code, rather than using a string literal. This is what a constant is. It is, in effect, a special kind of variable that cannot be varied when the program is running. In the next Try It Out, you learn to use constants. 1. Create a new Windows Forms Application in Visual Studio 2008 called Constants Demo. 2. When the Forms Designer appears, add three Button controls. Set the Name property of the first button to btnOne, the second to btnTwo, and the third to btnThree. Change the Text property of each to One, Two, and Three, respectively. Arrange the controls on your form so it looks similiar Figure 5-11. Try It Out Using Constants Figure 5-11 c05.indd 153c05.indd 153 4/2/08 5:31:50 PM4/2/08 5:31:50 PM Chapter 5: Working with Data Structures 154 3. View the Code Editor for the form by right-clicking the form and choosing View Code from the context menu. At the top of the class definition, add the following highlighted code: Public Class Form1 ‘File name constant Private Const strFileName As String = “C:\Temp\Hello.txt” 4. In the Class Name combo box at the top of the editor, select btnOne, and in the Method Name combo box select the Click event. Add the following highlighted code to the Click event handler: Private Sub btnOne_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnOne.Click ‘Using a constant MessageBox.Show(“1: “ & strFileName, “Constants Demo”) End Sub 5. Select btnTwo in the Class Name combo box and select its Click event in the Method Name combo box. Add the highlighted code: Private Sub btnTwo_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnTwo.Click ‘Using the constant again MessageBox.Show(“2: “ & strFileName, “Constants Demo”) End Sub 6. Select btnThree in the Class Name combo box and the Click event in the Method Name combo box. Add this code to the Click event handler: Private Sub btnThree_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnThree.Click ‘Reusing the constant one more time MessageBox.Show(“3: “ & strFileName, “Constants Demo”) End Sub 7. Save and run your project and then click button One. You’ll see the message box shown in Figure 5-12. Figure 5-12 c05.indd 154c05.indd 154 4/2/08 5:31:51 PM4/2/08 5:31:51 PM Chapter 5: Working with Data Structures 155 Likewise, you’ll see the same file name when you click buttons Two and Three. How It Works A constant is actually a type of value that cannot be changed when the program is running. It is defined as a variable, but you add Const to the definition indicating that this variable is constant and cannot change. ‘File name constant Private Const strFileName As String = “C:\Temp\Hello.txt” You’ll notice that it has a data type, just like a variable, and you have to give it a value when it’s defined — which makes sense, because you can’t change it later. When you want to use the constant, you refer to it just as you would refer to any variable: Private Sub btnOne_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnOne.Click ‘Using a constant MessageBox.Show(“1: “ & strFileName, “Constants Demo”) End Sub As mentioned before, the appeal of a constant is that it allows you to change a value that’s used throughout a piece of code by altering a single piece of code. However, note that you can change constants only at design time; you cannot change their values at runtime. Look at how this works. Different Constant Types In this section, you’ve seen how to use a string constant, but you can use other types of variables as constants. There are some rules: Basically, a constant must not be able to change, so you should not store an object data type (which we will discuss in Chapter 11) in a constant. Integers are very common types of constants. They can be defined like this: Public Const intHoursAsleepPerDay As Integer = 8 Also, it’s fairly common to see constants used with enumerations, like this: Public Const intRichardsTypicalState As DayAction = DayAction.AtWork Structures Applications commonly need to store several pieces of information of different data types that all relate to one thing and must be kept together in a group, such as a customer’s name and address (strings) and balance (a number). Usually, an object of a class is used to hold such a group of variables, as you’ll c05.indd 155c05.indd 155 4/2/08 5:31:51 PM4/2/08 5:31:51 PM Chapter 5: Working with Data Structures 156 discover in Chapter 11, but you can also use a structure. Structures are similar to class objects but are somewhat simpler, so they’re discussed here. Later on, as you design applications, you need to be able to decide whether to use a structure or a class. As a rule of thumb, we suggest that if you end up putting a lot of methods on a structure, it should probably be a class. It’s also relatively tricky to convert from a structure to a class later on, because structures and objects are created using different syntax rules, and sometimes the same syntax produces different results between structures and objects. So choose once and choose wisely! Building Structures Take a look at how you can build a structure. Try It Out Building a Structure 1. Create a new Windows Forms Application in Visual Studio 2008 called Structure Demo. 2. When the Forms Designer appears add four Label controls, four TextBox controls, and a Button control. Arrange your controls so that they look similar to Figure 5-13. 3. Set the Name properties as follows: ❑ Set Label1 to lblName. ❑ Set TextBox1 to txtName. ❑ Set Label2 to lblFirstName. ❑ Set TextBox2 to txtFirstName. ❑ Set Label3 to lblLastName. ❑ Set TextBox3 to txtLastName. ❑ Set Label4 to lblEmail. ❑ Set TextBox4 to txtEmail. ❑ Set Button1 to btnListCustomer. 4. Set the Text properties of the following controls: ❑ Set lblName to Name. ❑ Set lblFirstName to First Name. ❑ Set lblLastName to Last Name. ❑ Set lblEmail to E-mail. ❑ Set btnListCustomer to List Customer. c05.indd 156c05.indd 156 4/2/08 5:31:52 PM4/2/08 5:31:52 PM Chapter 5: Working with Data Structures 157 5. Right-click the project name in the Solution Explorer, choose the Add menu item from the con- text menu, and then choose the Class submenu item. In the Add New Item – Structure Demo dialog box, enter Customer in the Name field and then click the Add button to have this item added to your project. 6. When the Code Editor appears, replace all existing code with the following code: Public Structure Customer ‘Public members Public FirstName As String Public LastName As String Public Email As String End Structure Note that you must make sure to replace the Class definition with the Structure definition! 7. View the Code Editor for the form and add this procedure: Public Class Form1 Public Sub DisplayCustomer(ByVal customer As Customer) ‘Display the customer details on the form txtFirstName.Text = customer.FirstName txtLastName.Text = customer.LastName txtEmail.Text = customer.Email End Sub 8. In the Class Name combo box at the top of the editor, select btnListCustomer, and in the Method Name combo box select the Click event. Add the following highlighted code to the Click event handler: Private Sub btnListCustomer_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnListCustomer.Click ‘Create a new customer Dim objCustomer As Customer objCustomer.FirstName = “Michael” objCustomer.LastName = “Dell” objCustomer.Email = “mdell@somecompany.com” ‘Display the customer DisplayCustomer(objCustomer) End Sub Figure 5-13 c05.indd 157c05.indd 157 4/2/08 5:31:52 PM4/2/08 5:31:52 PM Chapter 5: Working with Data Structures 158 9. Save and run your project. When the form appears, click the List Customer button and you should see results similar to those shown in Figure 5-14. Figure 5-14 How It Works You define a structure using a Structure End Structure statement. Inside this block, the vari- ables that make up the structure are declared by name and type: These variables are called members of the structure. Public Structure Customer ‘Public members Public FirstName As String Public LastName As String Public Email As String End Structure Notice the keyword Public in front of each variable declaration as well as in front of the Structure statement. You have frequently seen Private used in similar positions. The Public keyword means that you can refer to the member (such as FirstName) outside of the definition of the Customer structure itself. In the btnListCustomer_Click procedure, you define a variable of type Customer using the Dim statement. (If Customer were a class, you would also have to initialize the variable by setting objCustomer equal to New Customer, as will be discussed in Chapter 11.) Private Sub btnListCustomer_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnListCustomer_Click.Click ‘Create a new customer Dim objCustomer As Customer Then you can access each of the member variables inside the Customer structure objCustomer by giving the name of the structure variable, followed by a dot, followed by the name of the member: objCustomer.FirstName = “Michael” objCustomer.LastName = “Dell” objCustomer.Email = “mdell@somecompany.com” ‘Display the customer DisplayCustomer(objCustomer) End Sub c05.indd 158c05.indd 158 4/2/08 5:31:53 PM4/2/08 5:31:53 PM Chapter 5: Working with Data Structures 159 The DisplayCustomer procedure simply accepts a Customer structure as its input parameter and then accesses the members of the structure to set the Text properties of the text boxes on the form: Public Sub DisplayCustomer(ByVal customer As Customer) ‘Display the customer details on the form txtFirstName.Text = customer.FirstName txtLastName.Text = customer.LastName txtEmail.Text = customer.Email End Sub Adding Properties to Structures You can add properties to a structure, just as you did to the form in the Enum Demo project earlier in the chapter. You learn how in the next Try It Out. 1. Open the Code Editor for Customer and add this highlighted code to create a read-only property Name: ‘Public members Public FirstName As String Public LastName As String Public Email As String ‘Name property Public ReadOnly Property Name() As String Get Return FirstName & “ “ & LastName End Get End Property 2. Open the Code Editor for Form1. Modify the DisplayCustomer method with the highlighted code: Public Sub DisplayCustomer(ByVal customer As Customer) ‘Display the customer details on the form txtName.Text = customer.Name txtFirstName.Text = customer.FirstName txtLastName.Text = customer.LastName txtEmail.Text = customer.Email End Sub 3. Run the project and click the List Customer button. You’ll see that the Name text box, which was empty in Figure 5-14, is now populated with the customer’s first and last name. Try It Out Adding a Name Property c05.indd 159c05.indd 159 4/2/08 5:31:55 PM4/2/08 5:31:55 PM Chapter 5: Working with Data Structures 160 Working with ArrayLists Suppose you need to store a set of Customer structures. You could use an array, but in some cases the array might not be so easy to use. ❑ If you need to add a new Customer to the array, you need to change the size of the array and insert the new item in the new last position in the array. (You’ll learn how to change the size of an array later in this chapter.) ❑ If you need to remove a Customer from the array, you need to look at each item in the array in turn. When you find the one you want, you have to create another version of the array one element smaller than the original array and copy every item except the one you want to delete into the new array. ❑ If you need to replace a Customer in the array with another customer, you need to look at each item in turn until you find the one you want and then replace it manually. The ArrayList provides a way to create an array that can be easily manipulated as you run your program. Using an ArrayList Look at using an ArrayList in this next Try It Out. 1. Return to the Structure Demo project in Visual Studio 2008. Make the form larger, move the existing controls down, and then add a new ListBox control as shown in Figure 5-15. Set the Name property of the list box to lstCustomers and its IntegralHeight property to False. You can click the form and press Ctrl+A to select all of the controls and then drag them to their new location. Try It Out Using an ArrayList Figure 5-15 c05.indd 160c05.indd 160 4/2/08 5:31:55 PM4/2/08 5:31:55 PM [...]... you can instruct Visual Basic 2008 to not clear the existing items One thing to remember is that if you make an array smaller than it originally was, data will be lost from the eliminated elements even if you use Preserve In the next Try It Out, you use Preserve 182 c05.indd 182 4/2/08 5 :32 :05 PM Chapter 5: Working with Data Structures Try It Out 1 Using Preserve Return to Visual Studio 2008, open the... c05.indd 176 4/2/08 5 :32 : 03 PM Chapter 5: Working with Data Structures 2 To demonstrate how a Hashtable cannot use the same key twice, run your project and click the List Customer button to have the customer list loaded Now click the List Customer button again and you’ll see the error message shown in Figure 5-22: Figure 5-22 3 Click the Stop Debugging button on the toolbar in Visual Studio 2008 to stop the... applications in Visual Studio 2008 What Is XAML? As previously mentioned, XAML is an Extensible Application Markup Language But what exactly does this mean? Wikipedia (www.wikipedia.org) defines XAML as a declarative XML-based language used to initialize structured values and objects Others define XAML as a declarative XML-based language that defines objects and their properties c06.indd 185 4/2/08 5 :32 :33 PM... visualize that this new language defines an application’s UI in an XML-type language by defining the controls on a form The controls that XAML defines map to classes in the NET Framework Keep in mind that XAML is an application markup language used to define a user interface and should not be confused with a programming language such as Visual Basic 2008 To illustrate this point, take a look at a basic. .. 5-16 161 c05.indd 161 4/2/08 5 :31 :57 PM Chapter 5: Working with Data Structures You are adding Customer structures to the list, but they are being displayed by the list as Structure_ Demo.Customer; this is the full name of the structure The ListBox control accepts string values, so, by specifying that you wanted to add the Customer structure to the list box, Visual Basic 2008 called the ToString method... at these, you moved on to look at various types of collections, including the basic ArrayList and then saw how you could build your own powerful collection classes inherited from CollectionBase Finally, you looked at the Hashtable class and covered some of the less commonly used array functionality 1 83 c05.indd 1 83 4/2/08 5 :32 :06 PM Chapter 5: Working with Data Structures To summarize, you should know... XAML, which is stored in a file with a xaml extension The developer would import that XAML file into Visual Studio 2008 and then write the code to make the form shown in Figure 6-1 have functional meaning so that when the user clicks the button something useful happens 186 c06.indd 186 4/2/08 5 :32 :34 PM ... Array Demo project in Visual Studio 2008 Open the Code Editor for Form1 and modify the code in the AddItemsToList method so that it looks like this: Private Sub AddItemsToList(ByVal arrayList() As String) ‘Enumerate the array For Each strName As String In arrayList ‘Add the array item to the list lstFriends.Items.Add(“[“ & strName & “]”) Next End Sub 180 c05.indd 180 4/2/08 5 :32 :04 PM Chapter 5: Working... c05.indd 180 4/2/08 5 :32 :04 PM Chapter 5: Working with Data Structures 2 Run the project and click the Initializing Arrays with Values button Your form should look like Figure 5- 23; note the square brackets around each name Figure 5- 23 3 Stop the project and make the highlighted change to the btnInitializingArraysWithValues_Click method: Private Sub btnInitializingArraysWithValues_Click( _ ByVal sender As... way to go and one that you’ll be familiar with Adding an Item Property At the beginning of this section, you read that you were supposed to add two methods and one property You’ve seen the methods but not the property, so take a look at it in the next Try It Out Try It Out 1 Adding an Item Property Return to Visual Studio 2008, open the Code Editor for the CustomerCollection class, and add this code: . 5-11. Try It Out Using Constants Figure 5-11 c05.indd 153c05.indd 1 53 4/2/08 5 :31 :50 PM4/2/08 5 :31 :50 PM Chapter 5: Working with Data Structures 154 3. View the Code Editor for the form by right-clicking. >= 22 And value < 23 Then CurrentState = DayAction.GettingReadyForBed Else CurrentState = 999 End If If you build the project, you’ll notice that Visual Basic 2008 doesn’t flag this as. the customer DisplayCustomer(objCustomer) End Sub c05.indd 158c05.indd 158 4/2/08 5 :31 : 53 PM4/2/08 5 :31 : 53 PM Chapter 5: Working with Data Structures 159 The DisplayCustomer procedure simply

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan