Query a dataset using LINQ

Query a dataset using LINQ
Dr.NaveenBansal Profile Pic
Dr.NaveenBansal,India,Teacher
Published Date:25-10-2017
Your Website URL(Optional)
Comment
CHAPTER25 The Missing “LINQ” (Querying a Database) After studying Chapter 25, you should be able to: Query a dataset using LINQ Use the LINQ aggregate operators462 CHAPTER 25 The Missing “LINQ” (Querying a Database) Asking Questions In Chapter 24, you learned how to use the Data Source Configuration Wizard to connect an application to a database, thereby creating a dataset. Recall that a dataset is a copy of the fields and records the application can access from the database. The dataset is stored in the computer’s internal memory while the application is running. You also learned how to display the fields and records by binding table and field objects to controls in the interface. In Chapter 24, all of the records were displayed in the order they appeared in the database. In this chapter, you will learn how to display the records in a particular order, as well as how to display only records that meet specific criteria. The examples in this chapter use the Employees database from Chapter 24. The database, which contains one table named tblEmploy, is shown in Figure 25-1. The table contains seven fields and 14 records. The Emp_Number field is the primary key, because it uniquely identifies each record in the table. The Status field contains the employment status, which is either the letter F (for full-time) or the letter P (for part-time). The Code field identifies the employee’sdepartment:1forAccounting,2forAdvertising,3forPersonnel,and4for Inventory. field names records Figure 25-1 Data contained in the tblEmploy table You use a query to specify both the records to select in a dataset and the order in which to arrange the records. You can create a query in Visual Basic 2010 using a language feature called Language Integrated Query or, more simply, LINQ.Figure25-2showsthebasicsyntax of LINQ when used to select and arrange records in a dataset. The figure also includes examples of using the syntax. In the syntax, variableName and elementName can be any names you choose, as long as the name follows the naming rules for variables. In other words, there is nothing special about the records and employee names used in the examples. The Where and Order By clauses are optional parts of the syntax. You use the Where clause, which contains a condition, to limit the records you want to view. Similar to the condition in If…Then…Else and Do…Loop statements, the condition in a Where clause specifies a requirement that must be met for a record to be selected. The Order By clause is used to arrange(sort)therecordsineitherascending(thedefault)ordescendingorderbyoneormore fields.Noticethatthesyntaxdoesnotrequireyoutospecifythedatatype ofthevariable inthe Dim statement. Instead, the syntax allows the computer to infer the data type from the value being assigned to the variable. The statement in Example 1 in Figure 25-2 selects all of the records in the dataset and assigns the records to the records variable. The statement in Example 2 performs the same task; however, the records are assigned in ascending order by the Code field. If you are sorting records in ascending order, you do not need to include the keyword Ascending in the Order By clause, because Ascending is the default. The statement in Example 3 assigns only the records for part-time employees to the records variable. The statement in Example 4 performs the same task; however, the records are assigned in descending order by the Code field. The statement in Example 5 uses the Like operator and the asterisk pattern-matching character to463 Asking Questions select only records whose First_Name field begins with the letter J. You learned about the Like operator and its pattern-matching characters in Chapter 23. Using LINQ to select and arrange records in a dataset Basic syntax Dim variableName = From elementName In dataset.table Where condition Order By elementName.fieldName1 Ascending Descending , elementName.fieldNameN Ascending Descending Select elementName Example 1 Dim records = From employee In EmployeesDataSet.tblEmploy Select employee selects all of the records in the dataset Exam ple 2 Dim records = From employee In EmployeesDataSet.tblEmploy Order By employee.Code Select employee selects all of the records in the dataset and arranges them in ascending order by the Code field Example 3 Dim records = From employee In EmployeesDataSet.tblEmploy Where employee.Status.ToUpper = "P" Select employee selects only the part-time employee records in the dataset Example 4 Dim records = From employee In EmployeesDataSet.tblEmploy Where employee.Status.ToUpper = "P" Order By employee.Code Descending Select employee selects only the part-time employee records in the dataset and arranges them in descending order by the Code field Example 5 Dim records = From employee In EmployeesDataSet.tblEmploy Where employee.First_Name.ToUpper Like "J" Select employee selects only the employee records in the dataset whose first name begins with the letter J Figure 25-2 Basic LINQ syntax and examples for selecting and arranging records in a dataset Revisiting the Raye Industries Application You coded two versions of the Raye Industries application in Chapter 24. In this chapter, you will modify the second version of the application. The modified application will display records whose Last_Name field begins with one or more letters entered by the user. It also will both calculate and display the average pay rate.464 CHAPTER 25 The Missing “LINQ” (Querying a Database) To begin modifying the Raye Industries application: 1. Start Visual Studio 2010 or Visual Basic 2010 Express. Open theRayeIndustriesSolution (Raye Industries Solution.sln) file contained in the ClearlyVB2010\Chap25\Raye Industries Solution folder. If the designer window is not open, double-click frmMain.vb in theSolutionExplorerwindow.TheinterfacewasmodifiedtodisplaytheFirst_Namefield.It also includes two new buttons: Find Record and Calculate Average. See Figure 25-3. Figure 25-3 Modified user interface for the Raye Industries application 2. Open the Code Editor window and locate the btnFind control’s Click event procedure. First, you will use the InputBox function to prompt the user to either enter one or more letters or leave the input area empty. Click the blank line below the ' get user input comment. Enter the following assignment statement: strSearch = InputBox(strPROMPT, "Find Last Name").ToUpper 3. Now you will enter the LINQ statement to select the appropriate records. Click the blankline below the 'selecttheappropriaterecords comment and then enter the following LINQ statement: Dim records = From employee In EmployeesDataSet.tblEmploy Where employee.Last_Name.ToUpper Like strSearch & "" Select employee Important note: If a jagged line appears below records in the LINQ statement, click Tools on the menu bar and then click Options. Expand the Projects and Solutions node and then click VB Defaults. Change Option Strict to Off and (if necessary) change Option Infer to On. The LINQ statement merely selects the records and assigns them to the records variable. To actually view the records, you need to assign the variable’s contents to the DataSource property of a BindingSource object. The syntax for doing this is shown in Figure 25-4 along with an example of using the syntax. Assigning a LINQ variable’s contents to a BindingSource object Basic syntax bindingSource.DataSource = variableName.AsDataView Example TblEmployBindingSource.DataSource = records.AsDataView assigns the contents of the records variable to the TblEmployBindingSource object Figure 25-4 Syntax and an example of assigning a LINQ variable’s contents to a BindingSource object465 Asking Questions To complete the btnFind control’s Click event procedure: 1. Click the blank line below the ' display the records comment and then enter the following assignment statement: TblEmployBindingSource.DataSource = records.AsDataView Figure 25-5 shows the code entered in the Find Record button’s Click event procedure. Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click ' displays records whose last name ' begins with the user's entry Const strPROMPT As String = "Enter one or more characters in the " & "last name. " & "Leave blank to retrieve all records." Dim strSearch As String ' get user input strSearch = InputBox(strPROMPT, "Find Last Name").ToUpper ' select the appropriate records Dim records = From employee In EmployeesDataSet.tblEmploy Where employee.Last_Name.ToUpper Like strSearch & "" Select employee ' display the records TblEmployBindingSource.DataSource = records.AsDataView End Sub Figure 25-5 Find Record button’s Click event procedure To test the btnFind control’s Click event procedure: 1. Save the solution and then start the application. First, you will select all of the records whose Last_Name field begins with the letter i. Click the FindRecord button. Typei in the Find Last Name dialog box and then press Enter. The first record that meets the criterion—the Asaad Ismal record—appears in the interface. Click the Next Record buttontodisplayRebeccaIovanelli’srecord.ClicktheNextRecordbuttonagain.Notice that Rebecca Iovanelli’s record is the last record that meets the criterion. 2. Now you will have the LINQ statement select all of the records. Click the Find Record button and then click theOK button. Click theNextRecord button repeatedly to verify that all 14 records have been retrieved. 3. Click the Exit button.466 CHAPTER 25 The Missing “LINQ” (Querying a Database) Mini-Quiz 25-1 See Appendix B for the answers. 1. Complete the Where clause in the following statement, which should select only records whose LastName field begins with an uppercase letter A: Dim records = From name In NamesDataSet.tblNames Where Select name 2. Complete the following statement, which should arrange the records in descending order by the LastName field: Dim records = From name In NamesDataSet.tblNames Select name 3. What does LINQ stand for? 4. In a LINQ statement, which clause is used to arrange the selected records in a particular order? a. Order c. Sort b. Order By d. Where 5. In a LINQ statement, which clause contains a condition? a. Order c. Sort b. Order By d. Where One for All In addition to using LINQ to sort and select the records in a dataset, you also can use it to perform arithmetic calculations on the fields in the records. The calculations are performed using the LINQ aggregate operators. The most commonly used aggregate operators are Average, Count, Max, Min, and Sum. An aggregate operator returns a single value from a group of values. The Sum operator, for example, returns the sum of the values in the group, whereas the Min operator returns the smallest value in the group. You include an aggregate operator in a LINQ statement using the syntax shown in Figure 25-6. The figure also includes examples of using the syntax. The statement in Example 1 calculates the average of the values contained in the Rate field, assigning the result to the dblAvgRate variable. The statement in Example 2 first selects only the part-time employee records. It then determines the highest value stored in the Rate field for those records. The statement assigns the result to the dblMaxRate variable. Example 3’s statement counts the number of employees in the Advertising department (Code = 2) and assigns the result to the intCounter variable.467 One for All LINQ aggregate operators Syntax Dim variableName As dataType = Aggregate elementName In dataset.table Where condition Select elementName.fieldName Into aggregateOperator() Example 1 Dim dblAvgRate As Double = Aggregate employee In EmployeesDataSet.tblEmploy Select employee.Rate Into Average() calculates the average of the pay rates in the dataset and assigns the result to the dblAvgRate variable Example 2 Dim dblMaxRate As Double = Aggregate employee In EmployeesDataSet.tblEmploy Where employee.Status.ToUpper = "P" Select employee.Rate Into Max() finds the highest pay rate for a part-time employee and assigns the result to the dblMaxRate variable Example 3 Dim intCounter As Integer = Aggregate employee In EmployeesDataSet.tblEmploy Where employee.Code = 2 Select employee.Emp_Number Into Count() counts the number of employees whose department code is 2 and assigns the result to the intCounter variable Figure 25-6 Syntax and examples of the LINQ aggregate operators You will use the Average aggregate operator to code the Calculate Average button’s Click event procedure. To code the Calculate Average button’s Click event procedure: 1. Locate the btnCalc control’s Click event procedure. First, you will enter the LINQ statement to calculate the average pay rate for all employees. Click theblankline below the ' calculate average pay rate comment and then enter the following LINQ statement: Dim dblAvgRate As Double = Aggregate employee In EmployeesDataSet.tblEmploy Select employee.Rate Into Average() 2. Now you will display the average pay rate in a message box. Click the blank line below the ' display average pay rate comment and then enter the following lines of code: MessageBox.Show("Average pay rate for all employees: " & dblAvgRate.ToString("C2"), "Raye Industries", MessageBoxButtons.OK, MessageBoxIcon.Information) Figure 25-7 shows the code entered in the Calculate Average button’s Click event procedure.468 CHAPTER 25 The Missing “LINQ” (Querying a Database) Private Sub btnCalc_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalc.Click ' displays the average pay rate ' calculate average pay rate Dim dblAvgRate As Double = Aggregate employee In EmployeesDataSet.tblEmploy Select employee.Rate Into Average() ' display average pay rate MessageBox.Show("Average pay rate for all employees: " & dblAvgRate.ToString("C2"), "Raye Industries", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Figure 25-7 Calculate Average button’s Click event procedure To test the Calculate Average button’s Click event procedure: 1. Save thesolution and thenstart the application.ClicktheCalculateAverage button. The average pay rate for all employees appears in a message box, as shown in Figure 25-8. To learn more about Figure 25-8 Average pay rate displayed in a message box LINQ, see the LINQ 2. Close the message box and then click the Exit button. Close the Code Editor window sectioninthe Ch25WantMore.pdf file. and then close the solution. Mini-Quiz 25-2 See Appendix B for the answers. 1. Complete the following statement, which should calculate the sum of the values stored in a numeric field named JanSales: Dim intTotal As Integer = Aggregate sales In SalesDataSet.tblSales Select Into Sum() 2. Complete the following statement, which should calculate the average of the values stored in a numeric field named PointsEarned: To review Dim dblAvg As Double = what you Aggregate points In PointsDataSet.tblPoints learned about LINQ, view the 3. Which of the LINQ aggregate operators returns the smallest value in the group? Ch25-LINQ video.469 Review Questions Summary l LINQ stands for Language Integrated Query. You can use LINQ to select and sort the records in a dataset. You also can use LINQ to perform calculations on the fields in the dataset. l LINQ provides the Average, Sum, Count, Min, and Max aggregate operators for performing calculations. Key Terms Aggregate operator—an operator that returns a single value from a group of values; LINQ provides the Average, Count, Max, Min, and Sum aggregate operators Language Integrated Query—LINQ; the query language built into Visual Basic 2010 LINQ—an acronym for Language Integrated Query Order By clause—used in LINQ to arrange (sort) the records in a dataset Query—specifies the records to select in a dataset and the order in which to arrange the records Where clause—used in LINQ to limit the records you want to view in a dataset Review Questions 1. Which of the following LINQ statements selects all of the records in the tblStates table? a. Dim records = From state In StatesDataSet.tblStates Select All state b. Dim records = From state In StatesDataSet.tblStates Select state c. Dim records = Select state From StatesDataSet.tblStates d. Dim records = From StatesDataSet.tblStates Select tblStates.state 2. The tblCities table contains a numeric field named Population. Which of the following LINQ statements selects all cities having a population that exceeds 15000? a. Dim records = From city In CitiesDataSet.tblCities Where Population 15000 Select city b. Dim records = From city In CitiesDataSet.tblCities Select city.Population 15000 c. Dim records = From city In CitiesDataSet.tblCities Where city.Population 15000 Select city d. Dim records = Select city.Population 15000 From tblCities470 CHAPTER 25 The Missing “LINQ” (Querying a Database) 3. The tblCities table contains a numeric field named Population. Which of the following LINQ statements calculates the total population of all the cities in the table? a. Dim intTotal As Integer = Aggregate city In CitiesDataSet.tblCities Select city.Population Into Sum() b. Dim intTotal As Integer = Sum city In CitiesDataSet.tblCities Select city.Population Into total c. Dim intTotal As Integer = Aggregate CitiesDataSet.tblCities.city Select city.Population Into Sum() d. Dim intTotal As Integer = Sum city In CitiesDataSet.tblCities.population 4. Which clause is used in a LINQ statement to limit the records that will be selected? a. Limit c. Select b. Order By d. Where 5. Which of the following LINQ statements arranges the records in ascending order by the LastName field, with records having the same last name arranged in descending order by the FirstName field? a. Dim records = From name In NamesDataSet.tblNames Order By name.LastName Ascending, name.FirstName Descending Select name b. Dim records = From name In NamesDataSet.tblNames Order By name.LastName, name.FirstName Descending Select name c. Dim records = Select name From NamesDataSet.tblNames Order By name.FirstName Descending, name.LastName d. both a and b 6. Which of the following will select only records whose CityName field begins with an uppercase letter S? a. Dim records = From name In CitiesDataSet.tblCities Where name.CityName Like "S" Select name b. Dim records = From CitiesDataSet.tblCities Select CityName Like "S"471 Exercises c. Dim records = From tblCities Where tblCities.CityName Like "S" Select name d. Dim records = From name In CitiesDataSet.tblCities Where tblCities.CityName Like "S" Select name 7. Which of the following determines the number of records in the tblBooks table? a. Dim intNum As Integer = Aggregate book In BooksDataSet.tblBooks Select book.Title In Count() b. Dim intNum As Integer = Aggregate book In BooksDataSet.tblBooks Select book.Title Into Count() c. Dim intNum As Integer = Aggregate book In BooksDataSet.tblBooks Select book.Title Into Sum() d. Dim intNum As Integer = Aggregate book In BooksDataSet.tblBooks Select book.Title Into Number() Exercises 1. Open the Magazine Solution (Magazine Solution.sln) file contained in the TRY THIS ClearlyVB2010\Chap25\Magazine Solution-TRY THIS 1 folder. If necessary, open the designer window. The application is connected to the Magazines database, which is stored in the Magazines.accdb file. The database contains a table named tblMagazine. The table has three fields; the Cost field is numeric, and the Code and MagName fields contain text. Start the application to view the records contained in the dataset. Stop the application and open the Code Editor window. Code the btnSort control’s Click event procedure so that it displays the records in descending order by the Cost field. Code the btnDisplayCode control’s Click event procedure so that it displays the record whose Code fieldcontains PG24. Codethe btnDisplayNamecontrol’s Click event procedure so that it displays only the Java record. Save the solution and then start and test the application.ClosetheCodeEditorwindowandthenclosethesolution.(SeeAppendixB for the answer.) 2. Open the Magazine Solution (Magazine Solution.sln) file contained in the TRY THIS ClearlyVB2010\Chap25\Magazine Solution-TRY THIS 2 folder. If necessary, open the designer window. The application is connected to the Magazines database, which is stored in the Magazines.accdb file. The database contains a table named tblMagazine. The table has three fields; the Cost field is numeric, and the Code and MagName fields contain text. Start the application to view the records contained in the dataset. Stop the application and open the Code Editor window. Code the btnDisplayCost control’s Click event procedure so that it displays records having a cost of at least 4. Code the btnDisplayName control’s Click event procedure so that it displays only magazines whose name begins with the letter C (in either uppercase or lowercase). Code the btnAverage control’s Click event procedure so that it displays the average cost of a magazine. Display the average in a message box. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. (See Appendix B for the answer.)472 CHAPTER 25 The Missing “LINQ” (Querying a Database) MODIFY THIS 3. In this exercise, you modify the Raye Industries application from the chapter. Use Windows to make a copy of the Raye Industries Solution folder. Save the copy in the ClearlyVB2010\Chap25 folder. Rename the copy Raye Industries Solution-MODIFY THIS. Open the Raye Industries Solution (Raye Industries Solution.sln) file contained in the Raye Industries Solution-MODIFY THIS folder. Open the designer window. Open the Code Editor window and locate the btnCalc control’s Click event procedure. Currently, the procedure displays the average pay rate for all employees. Modify the procedure so it displays three values in the message box: the average pay rate for part- time employees, the average pay rate for full-time employees, and the average pay rate for all employees. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. 4. In this exercise, you code a different version of the Raye Industries application from the INTRODUCTORY chapter. Open the Raye Industries Solution (Raye Industries Solution.sln) file contained in the ClearlyVB2010\Chap25\Raye Industries Solution-INTRODUCTORY folder. Open the Code Editor window. Code the btnDisplay control’s Click event procedure so that it asks the user for the department code (1, 2, 3, or 4); use the InputBox function. The procedure should display only records matching that department code. If the user enters an invalid department code, display an appropriate message. If the user does not enter a department code, display all the records. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. INTRODUCTORY 5. Open the Addison Playhouse Solution (Addison Playhouse Solution.sln) file contained in the ClearlyVB2010\Chap25\Addison Playhouse Solution folder. The application is connected to a Microsoft Access database named Play. The Play database contains one table named tblReservations. The table has 20 records. Each record has three fields: a numeric field named Seat and two text fields named Patron and Phone. Code the btnDisplay control’s Click event procedure so that it asks the user for one or more characters in the patron’s name; use the InputBox function. The procedure should displayonlyrecordswhosenamesbeginwiththosecharacters.Iftheuserdoesnotenter any characters in the InputBox function’s input area, the procedure should display all the records. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. 6. In this exercise, you modify the Raye Industries application from the chapter. Use INTERMEDIATE Windows to make a copy of the Raye Industries Solution folder. Save the copy in the ClearlyVB2010\Chap25folder.RenamethecopyRayeIndustriesSolution-INTERMEDIATE. Open the Raye Industries Solution (Raye Industries Solution.sln) file contained in the Raye Industries Solution-INTERMEDIATE folder. Open the designer window. Open the Code Editor window and locate the btnFind control’s Click event procedure. Modify the procedure’s code so that it displays (in a message box) the number of employees found. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. ADVANCED 7. Open the Books Solution (Books Solution.sln) file contained in the Books Solution folder. The application is connected to a Microsoft Access database named Books. The Books database contains one table named tblBooks. The table has 11 records. Each record has five fields. The BookNumber, Price, and QuantityInStock fields contain numbers. The Title and Author fields contain text. The btnCalc control’s Click event procedure should display (in a message box) the total value of the books in inventory. The total value is calculated by multiplying the quantity of each book by its price and then adding together the results. Code the procedure. Save the solution and then start and test the application. Close the Code Editor window and then close the solution.473 Exercises 8. In this exercise, you use a Microsoft Access database named Courses. The database is ADVANCED stored in the Courses.accdb file, which is located in the ClearlyVB2010\Chap25\Access Databases folder. The database contains one table named tblCourses. The table has 10 records, each having four fields: ID, Title, CreditHours, and Grade. The CreditHours field is numeric; the other fields contain text. Open the College Courses Solution (College Courses Solution.sln) file contained in the ClearlyVB2010\Chap25\College Courses Solution folder. Connect the application to the Courses database. Drag the table into the group box control and then dock the DataGridView control in its parent container. (In this case, the parent container is the group box control.) Use the DataGridView control’s task list to disable Adding, Editing, and Deleting. Change the DataGridView control’s AutoSizeColumnsMode property to Fill. Remove the BindingNavigator control from the form by deleting the BindingNavigator object from thecomponenttray.OpentheCodeEditorwindow.DeletetheSaveDatabutton’sClick event procedure. Code the Next Record and Previous Record buttons. Code the btnDisplay control’s Click event procedure so it allows the user to display either all the records or only the records matching a specific grade. Code the btnCalc control’s Click event procedure so it displays the student’s GPA. An A grade is worth 4 points, a B is worth 3 points, and so on. Save the solution and then start and test the application. Close the Code Editor window and then close the solution. 9. What task is performed by the following LINQ statement? FIGURE THIS OUT Dim decArea As Decimal = Aggregate rec In RectanglesDataSet.tblRectangles Select rec.Length rec.Width Into Min() 10. Open the SwatTheBugs Solution (SwatTheBugs Solution.sln) file contained in the SWAT THE BUGS ClearlyVB2010\Chap25\SwatTheBugs Solution folder. Open the Code Editor window and study the existing code. Start and then test the application. Notice that the application is not working correctly. Locate and correct the errors in the code. Save the solution and then start and test the application again. Close the Code Editor window and then close the solution.This page intentionally left blank CHAPTER26 I Love This Class (Creating a Class) After studying Chapter 26, you should be able to: Explain the terminology used in object-oriented programming Create a class Instantiate an object Add Property procedures to a class Include data validation in a class Create a default constructor Include methods other than constructors in a class476 CHAPTER 26 I Love This Class (Creating a Class) That’s a Real Classy Object Visual Basic 2010 is an object-oriented programming language,whichisalanguagethat allows the programmer to use objects to accomplish a program’sgoal.An object is anything that can be seen, touched, or used. In other words, an object is nearly any thing.The objects used in an object-oriented program can take on many different forms. The text boxes, labels, and buttons included in most Windows applications are objects, and so are the application’s named constants and variables. An object also can represent something found in real life, such as a credit card receipt or a paycheck. Every object used in an object-oriented program is created from a class, which is a pattern that the computer uses to create the object. Using object-oriented programming (OOP) terminology, objects are instantiated (created) from a class, and each object is referred to as an instance of the class. A button control, for example, is an instance of the Button class. The button is instantiated when you drag the Button tool from the toolbox to the form. A String variable, on the other hand, is an instance of the String class and is instantiated the first time you refer to the variable in code. Keep in mind that the class itself is not an object. Only an instance of a class is an object. Every object has attributes, which are the characteristics that describe the object. Attributes are also called properties. Included in the attributes of buttons and text boxes are the Name and Text properties. DataGridView controls have a DataSource property as well as an AutoSizeColumnsMode property. In addition to attributes, every object also has behaviors. An object’s behaviors include methods and events. Methods are the operations (actions) that the object is capable of performing. For example, a button control can use its Focus method to send the focus to itself. Events are the actions to which an object can respond. A button control’s Click event, for instance, allows the button to respond to a mouse click. Aclasscontains—or, in OOP terms, it encapsulates—all of the attributes and behaviors of the object it instantiates. The term “encapsulate” means “to enclose in a capsule.” In the context of OOP, the capsule is a class. In previous chapters, you instantiated objects using classes that are built into Visual Basic, such as the TextBox and Label classes. You used the instantiated objects in a variety of ways in many different applications. In some applications, you used a text box to enter a name, while in other applications you used it to enter a sales tax rate. Similarly, you used label controls to identify text boxes and also to display the result of calculations. The ability to use an object for more than one purpose saves programming time and money—an advantage that contributes to the popularity of object-oriented programming. Visual Basic also provides a way for you to define your own classes and then create instances (objects) from those classes. Like the classes built into Visual Basic, your classes must specify the attributes and behaviors of the objects they create. You define a class using the Class statement, which you enter in a class file. Figure 26-1 shows the statement’s syntax and lists the steps for adding a class file to an open project. Although it is not a requirement, the convention is to use Pascal case for the class name. Recall that Pascal case means you capitalize the first letter in the name and the first letter in any subsequent words in the name. The names of Visual Basic classes (for example, String and TextBox) also follow this naming convention. Within the Class statement, you define the attributes and behaviors of the objects the class will create. In most cases, the attributes are represented by variables and Property procedures. You will learn about Property procedures later in this chapter. The behaviors are represented by methods, which can be Sub or Function procedures. (Some behaviors are represented by Event procedures; however, that topic is beyond the scope of this book.) Also included in Figure 26-1 is an example of a Class statement that defines a class named RectangularPool.477 Revisiting the Willow Pools Application Class statement Syntax Public Class className attributes section behaviors section End Class Example Public Class RectangularPool attributes behaviors End Class Adding a class file to an open project 1. Click Project on the menu bar and then click Add Class. The Add New Item dialog box opens with Class selected in the middle column of the dialog box. 2. Type the name of the class followed by a period and the letters vb in the Name box, and then click the Add button. Figure 26-1 Class statement syntax, example, and steps You will use the Class statement in the Willow Pools application, which you begin coding in the next section. Revisiting the Willow Pools Application You coded theWillowPools application inChapter 21. As you mayremember, theapplication determines the amount of water required to fill a rectangular pool. To make this determination, the application first calculates the volume of the pool. Recall that you calculate the volume of a rectangular pool by multiplying the pool’slengthbyitswidthandthen multiplying the result by the pool’s depth. Assuming the length, width, and depth are measured in feet, this gives you the volume in cubic feet. To determine the number of gallons of water, the application multiplies the number of cubic feet by 7.48, because there are 7.48 gallons in one cubic foot. In Chapter 21, you used a structure to group together the pool’s length, width, and depth measurements. Recall that it’s logical to group the three items because they are related; each represents one of the three dimensions of a rectangular pool. Most of the application’s code from Chapter 21 is shown in Figure 26-2. However, unlike the code from Chapter 21, the code in Figure 26-2 uses the Decimal (rather than Double) data type. Also, the txtLength.Focus() statement was added to the btnCalc control’s Click event procedure. In this chapter, you will modify the code to use a class rather than a structure.478 CHAPTER 26 I Love This Class (Creating a Class) Structure Dimensions Public decLength As Decimal entered in the form’s Public decWidth As Decimal Declarations section Public decDepth As Decimal End Structure receives a structure Public Function GetGallons(ByVal pool As Dimensions) As Decimal variable by value ' calculates and returns the number of gallons Const decGAL_PER_CUBIC_FOOT As Decimal = 7.48 Return pool.decLength pool.decWidth pool.decDepth decGAL_PER_CUBIC_FOOT End Function Private Sub btnCalc_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalc.Click ' displays the number of gallons declares a structure variable to store the Dim poolSize As Dimensions input data Dim decGallons As Decimal Decimal.TryParse(txtLength.Text, poolSize.decLength) Decimal.TryParse(txtWidth.Text, poolSize.decWidth) Decimal.TryParse(txtDepth.Text, poolSize.decDepth) passes the structure variable to the decGallons = GetGallons(poolSize) GetGallons function lblGallons.Text = decGallons.ToString("N0") txtLength.Focus() End Sub Figure 26-2 Code for the Willow Pools application using a structure To begin creating a class in the Willow Pools application: 1. StartVisualStudio2010orVisualBasic 2010Express.OpentheWillowPoolsSolution (Willow PoolsSolution.sln) file contained in the ClearlyVB2010\Chap26\Willow Pools Solution folder. If the designer window is not open, double-click frmMain.vb in the Solution Explorer window. 2. If necessary, permanently display the Solution Explorer window. 3. First, you will use the Class statement to define a class named RectangularPool. As mentioned earlier, you enter a Class statement in a class file. Click Project on the menu bar and then click Add Class. The Add New Item dialog box opens with Class selected in the middle column of the dialog box. Change the filename in the Name box to RectangularPool.vb and then click the Add button. The RectangularPool.vb window opens and shows the code template for the Class statement. In addition, the RectangularPool.vb filename appears in the Solution Explorer window. See Figure 26-3. class filename Figure 26-3 Class statement entered in the RectangularPool.vb window479 Revisiting the Willow Pools Application In the context of OOP, a RectangularPool object has three attributes: a length, a width, and a depth. As mentioned earlier, the attributes are represented in the Class statement by variables and Property procedures. The variables appear first in the Class statement, followed by the Property procedures. In most cases, the variables are declared using the keyword Private. The Privatekeywordindicatesthatthevariablescanbeusedonlywithintheclassinwhichtheyare defined. WhennamingthePrivatevariables inaclass,manyprogrammersusetheunderscoreas the first character and then camel case for the remainder of the name. Following this naming convention, you will use the names decLength, decWidth, and decDepth for the Private variables in the RectangularPool class. To begin coding the RectangularPool class definition: 1. Auto-hide the Solution Explorer window and then click the blank line below the Public Class RectangularPool clause. 2. Enter the following three declaration statements. Press Enter twice after typing the last declaration statement. Private _decLength As Decimal Private _decWidth As Decimal Private _decDepth As Decimal Who Owns That Property? When an application instantiates an object, only the Public members of the object’s class are visible (available) to the application; the application cannot access the Private members of the class. Using OOP terminology, the Public members are “exposed” to the application, whereas the Private members are “hidden” from the application. In this case, the decLength, decWidth, and decDepth variables will be hidden from any application that contains an instance of theRectangularPool class.Foranapplicationto assigndata toorretrievedatafrom a Private variable in a class, it must use a Public property. In other words, an application cannot directly refer to a Private variable in a class. Rather, it must refer to the variable indirectly, through the use of a Public property. You create a Public property using a Property procedure whose procedure header begins with the keyword Public. A Public Property procedure creates a property that is visible to any application thatcontains an instance of the class. Thebasic syntax for creating a Publicproperty is shown in Figure 26-4 along with examples of Public properties. You should use nouns and adjectives to name a property and enter the name using Pascal case, as in Length and AnnualSales. The property’s dataType must match the data type of the Private variable associated with the property. Between a Property procedure’s header and footer, you include a Get block of code and a Set block of code. The code contained in the Get block allows an application to retrieve the contents of the Private variable associated with the property. The code in the Set block allows an application to assign a value to the Private variable associated with the property.480 CHAPTER 26 I Love This Class (Creating a Class) Basic syntax of a Public Property procedure Syntax procedure header Public Property propertyName As dataType Get instructions Return privateVariable End Get Set(ByVal value As dataType) instructions privateVariable = value defaultValue End Set procedure footer End Property Example 1 Private _decLength As Decimal Public Property Length As Decimal Get Return _decLength End Get Set(ByVal value As Decimal) If value 0 Then _decLength = value Else _decLength = 0 End If End Set End Property Example 2 Private _intAnnualSales As Integer Public Property AnnualSales As Integer Get Return _intAnnualSales End Get Set(ByVal value As Integer) _intAnnualSales = value End Set End Property Figure 26-4 Basic syntax and examples of a Public Property procedure The Get block in a Property procedure contains the Get statement, which begins with the keyword Get and ends with the keywords End Get. Most times, you will enter only the Return privateVariable instruction within the Get statement. The instruction directs the computertoreturn thecontentsofthePrivatevariableassociatedwiththe property.InExample 1in Figure 26-4, the Return decLength statement tellsthe computerto returnthe contents of the decLength variable, which is the Private variable associated with the Length property. Similarly, the Return intAnnualSales statement in Example 2 tells the computer to return the contents of the intAnnualSales variable, which is the Private variable associated with the AnnualSales property. The Set block in a Property procedure contains the Set statement, which begins with the keyword Set and ends with the keywords End Set. Following the Set keyword is a parameter enclosed in parentheses. The parameter begins with the keywords ByVal value As. The keywords are followed by a dataType, which must match the data type of the Private variable

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.