Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
226
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 5

Later on, as you design applications, you will 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.Using Visual Studio 2005, create a new Windows Application project. Call it Structure Demo.

2.When the project is created, right-click the project name in the Solution Explorer, choose the Add menu item from the context menu, and then choose the Class submenu item. In the Add New Item – Structure Demo dialog box, enter a name of Customer in the Name field and then click the Add button to have this item added to your project.

3.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!

4.Open the Designer for Form1. Add four Label controls, four TextBox controls, and a Button control. Arrange your controls so that they look similar to Figure 5-13.

5.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 btnTest.

146

Working with Data Structures

6.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 btnTest to Test.

Figure 5-13

7.Double-click the button to create a new Click event handler. Add the following highlighted code. You’ll receive an error message that DisplayCustomer is not defined; ignore this error, because you’ll create the DisplayCustomer method in the next step:

Private Sub btnTest_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnTest.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

8.Next, add this procedure:

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

9.Run your project and click the Test button, and you should see results similar to those shown in Figure 5-14.

147

Chapter 5

Figure 5-14

How It Works

You define a structure using a Structure . . . End Structure statement. Inside this block, the variables 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 btnTest_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 10.)

Private Sub btnTest_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnTest.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

148

Working with Data Structures

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.

Try It Out

Adding a Name Property

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.Now, 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 Test 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.

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.

149

Chapter 5

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.

Try It Out

Using an ArrayList

1.Switch to the Form Designer and rearrange the controls on the form and 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.

Figure 5-15

2.Open the Code Editor for Form1 and add the member highlighted here to the top of the class definition:

Public Class Form1

‘Form level members

Private objCustomers As New ArrayList

150

Working with Data Structures

3.Now, add this method to Form1 to create a new customer:

Public Sub CreateCustomer(ByVal firstName As String, _

ByVal lastName As String, ByVal email As String)

‘Declare a Customer object Dim objNewCustomer As Customer

‘Create the new customer objNewCustomer.FirstName = firstName objNewCustomer.LastName = lastName objNewCustomer.Email = email

‘Add the new customer to the list objCustomers.Add(objNewCustomer)

‘Add the new customer to the ListBox control lstCustomers.Items.Add(objNewCustomer)

End Sub

4.Modify the btnTest_Click method next, making these code changes:

Private Sub btnTest_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnTest.Click

‘Create some customers

CreateCustomer(“Darrel”, “Hilton”, “dhilton@somecompany.com”)

CreateCustomer(“Frank”, “Peoples”, “fpeoples@somecompany.com”)

CreateCustomer(“Bill”, “Scott”, “bscott@somecompany.com”)

End Sub

5.Run the project and click the Test button. You’ll see results like those shown in Figure 5-16.

Figure 5-16

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 2005 called the

151

Chapter 5

ToString method of the Customer structure. By default, the ToString method for a structure returns the structure name, not the contents that you wanted to see. So what you want to do is tweak Customer so that it can display something more meaningful. Once you do that in the next Try It Out, you’ll see how the ArrayList works.

Try It Out

Overriding ToString

1.Open the Code Editor for Customer and add this method to the structure, ensuring that it is below the member declarations. Remember from Chapter 3 that to insert an XML Document Comment block, you type three apostrophes above the method name:

‘’’ <summary>

‘’’ Overrides the default ToString method ‘’’ </summary>

‘’’ <returns>String</returns>

‘’’ <remarks>Returns the customer name and email address</remarks> Public Overrides Function ToString() As String

Return Name & “ (“ & Email & “)” End Function

2.Run the project and click the Test button. You’ll see the same results as shown in Figure 5-17.

Figure 5-17

How It Works

Whenever a Customer structure is added to the list, the list box calls the ToString method on the structure to get a string representation of that structure. With this code, you override the default functionality of ToString so that, rather than returning just the name of the structure, you get some useful text:

‘’’ <summary>

‘’’ Overrides the default ToString method ‘’’ </summary>

‘’’ <returns>String</returns>

‘’’ <remarks>Returns the customer name and email address</remarks> Public Overrides Function ToString() As String

Return Name & “ (“ & Email & “)” End Function

152

Working with Data Structures

An ArrayList can be used to store a list of objects/structures of any type (in contrast to a regular array). In fact, you can mix the types within an ArrayList — a topic we’ll be talking about in a little while. In this example, you created a method called CreateCustomer that initializes a new Customer structure based on parameters that were passed to the method:

Public Sub CreateCustomer(ByVal firstName As String, _

ByVal lastName As String, ByVal email As String)

‘Declare a Customer object Dim objNewCustomer As Customer

‘Create the new customer objNewCustomer.FirstName = firstName objNewCustomer.LastName = lastName objNewCustomer.Email = email

Once the structure has been initialized, you add it to the ArrayList stored in objCustomers:

‘Add the new customer to the list objCustomers.Add(objNewCustomer)

You also add it to the list box itself, like this:

‘Add the new customer to the ListBox control lstCustomers.Items.Add(objNewCustomer)

With CreateCustomer defined, you can just call it to add new members to the ArrayList and to the list box control when the user clicks the Test button:

Private Sub btnTest_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnTest.Click

‘Create some customers

CreateCustomer(“Darrel”, “Hilton”, “dhilton@somecompany.com”) CreateCustomer(“Frank”, “Peoples”, “fpeoples@somecompany.com”) CreateCustomer(“Bill”, “Scott”, “bscott@somecompany.com”)

End Sub

Deleting from an ArrayList

OK, so now you know the principle behind an ArrayList. You use it to do something that’s traditionally hard to do with arrays but is pretty easy to do with an ArrayList, such as dynamically adding new values. Now let’s look at how easy it is to delete items from an ArrayList.

Try It Out

Deleting Customers

1.Using the Forms Designer, add a new Button control to the bottom of the form and set its Name property to btnDelete and its Text property to Delete.

153

Chapter 5

2.Double-click the button and add the highlighted code. You’ll receive an error message that SelectedCustomer is not defined; ignore this error, because you’ll add the SelectedCustomer function in the next step:

Private Sub btnDelete_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnDelete.Click

‘If no customer is selected in the ListBox then...

If lstCustomers.SelectedIndex = -1 Then

‘Display a message

MessageBox.Show(“You must select a customer to delete.”, _ “Structure Demo”)

‘Exit this method Exit Sub

End If

‘Prompt the user to delete the selected customer

If MessageBox.Show(“Are you sure you want to delete “ & _

SelectedCustomer.Name & “?”, “Structure Demo”, _

MessageBoxButtons.YesNo, MessageBoxIcon.Question) = _

DialogResult.Yes Then

‘Get the customer to be deleted

Dim objCustomerToDelete As Customer = SelectedCustomer

‘Remove the customer from the ArrayList objCustomers.Remove(objCustomerToDelete)

‘Remove the customer from the ListBox lstCustomers.Items.Remove(objCustomerToDelete)

End If End Sub

3.Next, add the SelectedCustomer property to the form as follows:

Public ReadOnly Property SelectedCustomer() As Customer

Get

If lstCustomers.SelectedIndex <> -1 Then

‘Return the selected customer

Return lstCustomers.Items(lstCustomers.SelectedIndex)

End If

End Get

End Property

4.Run the project and click the Test button. Do not select a customer in the list box and then click the Delete button. You’ll see a message box indicating that you must select a customer.

5.Now select a customer and click Delete. You’ll see a confirmation dialog box similar to the one shown in Figure 5-18.

6.Click Yes, and the person you selected will be removed from the list.

154

Working with Data Structures

Figure 5-18

How It Works

The trick here is to build a read-only property that will return the Customer structure that’s selected in the list box back to the caller on demand. The SelectedIndex property of the list box will return a value of -1 if no selection has been made. Otherwise it will return the zero-based index of the selected customer.

Public ReadOnly Property SelectedCustomer() As Customer

Get

If lstCustomers.SelectedIndex <> -1 Then

‘Return the selected customer

Return lstCustomers.Items(lstCustomers.SelectedIndex)

End If

End Get

End Property

Like the Name property that you added to the Customer structure, this property is identified as readonly by the keyword ReadOnly. It contains a Get block but no Set block. The reason for making it readonly is that it constructs the value it returns from other information (the contents of the Customer structures in the list) that can be set and changed by other means.

Inside the Click event handler for the Delete button, you first test to see whether a customer has been selected in the list box. If no customer has been selected, you display a message box indicating that a customer must be selected. Then you exit the method allowing the user to select a customer and try again:

‘If no customer is selected in the ListBox then...

If lstCustomers.SelectedIndex = -1 Then

‘Display a message

MessageBox.Show(“You must select a customer to delete.”, _ “Structure Demo”)

‘Exit this method Exit Sub

End If

155