Unit 15 Object-Oriented Programming Controls, Properties and Methods Contents Introduction .................................................................................................................... 3 Controls .......................................................................................................................... 3 Properties ....................................................................................................................... 7 Methods.......................................................................................................................... 9 OO and Control Objects and Code Reuse.................................................................... 14 Displaying Images in PictureBoxes ............................................................................. 18 Exercise 1 ................................................................................................................. 21 Completing the Program .............................................................................................. 21 Message Boxes......................................................................................................... 21 Exercise 2 ................................................................................................................. 23 Summary ...................................................................................................................... 24 © Peter Bilbie 2011-12 Page 2 of 24 Introduction VB .NET is very useful to developers who want to create interfaces very quickly. MDI applications can be created with menus allowing access to other forms and functionality within the application. The IDE also allows the developer to rapidly design various forms by simply dragging and dropping controls available from the Toolbox onto the forms. The designs – which may have very limited functionality – can be shown to the client to demonstrate the navigation through the application and for the client to verify how the design matches their requirements. This is why VB .NET is an ideal tool for Rapid Application Development (RAD) To demonstrate this concept we will be (rapidly) creating a simple input form for a travel agency application from the given specification below: Cosy Cottages (Britain) wants an application to allow their operatives to add details of customer lettings– name, address, number of adults, children etc. The application must also display a list of cottages available, images of the cottages, insurance agreed (yes or no) and the start and end dates for the holiday. There must also be facilities to allow saving the data to a database and printing out the booking Controls To achieve the above task we will need an application consisting of one form containing various controls. Below is a list of the most common controls that are used to develop applications Control Textbox Label Command Button List Box Combo Box Check Box Radio Button Date/Time Picker Picture Box Purpose Used or inputting text or numbers and displaying results of computations Mainly used for labelling other controls Used for executing various actions Used to list/display and select items in list format As a list box but in drop-down list format Can only be checked (ticked) or unchecked – used for true or false situations Mainly used in sets to allow the user to choose which one of the set is applicable i.e. ‘male’, ‘female’ or ‘other’ Used to choose dates from a calendar Used to display images © Peter Bilbie 2011-12 Page 3 of 24 For this exercise we are going to use all of the above controls to create a simple input form for the cottage letting application Open the MDI application that we created last session by locating the folder wherever you have saved it. The folder should look like the example below: Double click on the folder and inside there is file icon with the name you assigned to the project – double click the icon to open the project IDE Also in the folder is another folder that contains the files that were either created by you i.e. Forms, or generated internally by the IDE. They also contain all the information needed to execute the program – see below © Peter Bilbie 2011-12 Page 4 of 24 During last sessions exercise you should have created a form named frmCosyCottages – this is the form we are going to use for this session’s exercise. Double-click on the forms icon in the Solution explorer and the form should be displayed in the design window – see below Before we start adding any controls to the form we need to give it a suitable caption by changing the Text property of the form from frmCosyCottages to Cosy Cottage Holidays. Do not change the (Name) property of either the form or the menu item – just the Text property © Peter Bilbie 2011-12 Page 5 of 24 To produce a solution to the Cosy Cottages specification we start by identifying the required input controls for customer information i.e. a set of textboxes – one each for surname, forename, address To add textboxes locate the TextBox icon in the Toolbox located on the left hand side of the design window – see below. Double-click on the icon and a textbox will be added to the form. Repeat to add the other textboxes – see below Add labels to identify each textbox. The form should then look as below. Reposition the textboxes so that each textbox has a label and they are in line We now need to decide how the other data is displayed or input. My suggestions are: © Peter Bilbie 2011-12 Page 6 of 24 Number of Adults and Children – Combo Box x 2 List of Cottages – list box Images of Cottages - Picturebox Insurance – check box x 1 Start and End dates - Date/Time Picker x 2 Save, Print confirmation and Close – Button x 3 We can add these controls to the form and if you need more room you can re-size the form by using the re-size handles on the edge of the form. My design is shown below – I have added more labels for some of the new controls Properties We now need to change some of the properties of the controls to make the interface understandable to both the developer and the end user. The first property we will change is the (Name) property of all the controls using the correct prefixes and naming conventions discussed in the unit introduction – a revised list is shown below. For example, the three buttons may be named btnSave, © Peter Bilbie 2011-12 Page 7 of 24 btnPrint and btnClose. Remember to use lower case for the prefix and capitalise the first letter of each word in the name – spaces not allowed Control Prefix Label lbl Textbox txt Command Button btn Form Frm Combo Box cbo Check box chk List box lst Radio button rad Menu item mnu Timer Tmr Group box Grp Date/Time Picker dtp A quick way of changing the same property of any number of controls is to click on the first control you want to name – this will show the properties of that control in the Properties window. Scroll to the (Name) property and rename it. Click on the next control and start typing and it will automatically enter your typing in the (Name) property. Continue until all controls have been named. The (Name) property is the most important property as this is what the VB environment will use to identify each control The Text property of all the controls is the next to be changed. The labels need to contain suitable identifiers i.e. Surname, Postcode etc – see below. The textboxes and combo boxes need to be cleared of any data. The Check box has its own integral label which needs to be changed to reflect its usage. If we now run the program – F5 – and click on Form Design Exercise– see below we can now see what the interface will look like to the end user © Peter Bilbie 2011-12 Page 8 of 24 We can add text to the textboxes, check the insurance check box - tick or no tick -, and choose the start and end dates of the holiday using the date and time picker controls. All this is achieved without the developer writing one line of code apart from the code to open the form. You can see why VB is a good tool for rapid application development. We will need to add some code to the combo boxes, the list box and the command buttons to make the interface ‘appear’ to be fully functioning. Some of this can be done using a controls Event Procedures or by programming the controls Properties and Methods Methods Methods are programming constructs that perform an action or a service for a particular object. They are the public interface to a classes object. Methods differ from properties, which contain a value, and event procedures which execute when the user manipulates an object. A method is an action you can perform on a control, for example, textboxes have a ‘Clear’ method that clears the contents (changes the Text property) of a textbox when called. © Peter Bilbie 2011-12 Page 9 of 24 Aside - Dot Notation and Intellisense – preventing typo errors To view all the properties and methods for any control we need to go to the Code Window of the form – double click anywhere on the form or click on the .vb* tab. It is at this point that you realise the importance of giving all your controls suitable names because VB has a feature called Intellisense that allows the developer to type in the first few characters of a control name and when you hold the control key down and press the space bar (Ctrl-Space) the remainder of the name (if it exists) will be automatically filled in. This saves a lot of time and prevents many errors occurring. It doesn’t matter how quick you are at typing, always use Intellisense. When you have a correctly named the controls the methods and properties for the control are accessed when you type a dot (.) directly after the name – a list should appear. The screen-shot below shows the property/method list of a control named txtSurname The methods (functions or procedures) can be identified by purple book icon and the properties by a letter in a hand icon – see below. If you scroll down the list you can see that there are many more properties available in code than there is in the properties window. Property icon Method icon What we need to do now is to add some items to the List box. This can be completed when the form is first ‘loaded’ (displayed) in the program. As previously mentioned, VB .NET is an Event Driven programming language and nothing will happen unless we assign code to an Event. For the purposes of this exercise, the Load event of the Form is where we want to add the code that is used to initialise any controls on the form. If you double-click on the form (not on any of the controls on the form) the code window will set the cursor in the forms Load event template – see below – this is where we will add our code © Peter Bilbie 2011-12 Page 10 of 24 The listbox control has an Items property that is a container for the list of items we want to add and an Add method which allows the developer to add items to the list. To access these properties and methods we need to add the control name i.e. lstCottage - don’t type in full just type lst then Ctrl-Space – then add a full-stop and the list should appear – see below. When you highlight the property or method that you want an explanation of the property/method is displayed. Add another full-stop and another list appears – highlight Add and add a left bracket – see below Inside the brackets we will add a ‘String’ parameter which needs to be in speech marks (more on this later), which is the name of a cottage – see below Private Sub frmCosyCottages_Load(ByVal… lstCottage.Items.Add("Pete's Place") End Sub This is the simplest method of ‘hard coding’ items in a listbox. Add the following cottages on separate lines. Private Sub frmCosyCottages_Load(ByVal… lstCottage.Items.Add("Pete's Place") lstCottage.Items.Add("Winkers Rest") lstCottage.Items.Add("Bolt Hole") lstCottage.Items.Add("Fishy") lstCottage.Items.Add("Haven") lstCottage.Items.Add("Juanita") lstCottage.Items.Add("Parkstone") lstCottage.Items.Add("Sheila's Shack") lstCottage.Items.Add("The Grimley's") lstCottage.Items.Add("Vickies") lstCottage.Items.Add("Pete's Place") End Sub © Peter Bilbie 2011-12 Page 11 of 24 Run the program – F5 – and look at the result – it should look as below You may have noticed that although the Picturebox has been added to the form, it does not appear when the program is executed. In design mode click on the Picturebox (picCottage) and set the BorderStyle property to FixedSingle – see below: However, although we can now see the empty Picturebox, it does not display any images of cottages. You can obtain a set of cottages images from your tutor or download them from the course wiki. Copy and paste all the images into your programs Debug folder that is located in the bin folder. To access the Debug folder, locate the main yellow program folder, wherever you saved it and double-click on the folder to open it – see below: © Peter Bilbie 2011-12 Page 12 of 24 Program Folder Inside the folder you will see several folders and files including the bin folder – see below: Double-click on the bin folder and then the Debug folder – see below: © Peter Bilbie 2011-12 Page 13 of 24 Copy and paste all the images into the Debug folder. When you are using an image you must map a path to the location where the image is stored i.e. C:\My Documents\Programming\Petesimages\PetesPlace.jpg However, by placing the images in the Debug folder we only have to identify the image name i.e. PetesPlace.jpg. This is because if the full path is not given the VB software will look in the Debug folder for the image. To see this in action we have to write some OO code. This requires some explanation. OO and Control Objects and Code Reuse We have been using OO concepts ever since we created the program for this exercise. Every form you create, including the MDI form is a class. If you look in the code window for the MDI form you will see the following code: Public Class frmMain Private Sub frmMain_Load(ByVal… End Sub Private Sub CottageLettingExerciseToolStripMenuItem_Click(ByVal… setForm(frmCosyCottages, Me) End Sub Private Sub ExitToolStripMenuItem_Click(ByVal… Application.Exit() End Sub End Class As you can see the first line of code declares the form as being a Public Class. When each form is created the VB Compiler Services provide the code that Inherits from a class named Form. The Form Class provides all the functionality i.e. Functions, Sub Procedures, Properties, and Event Procedures etc that are common to all Forms. We as programmers do not have to provide these elements as they have already been written. The complier gives the programmer a Class Template which has a (Name) property that is specified by the programmer i.e. frmMain. If we did not name any of the classes the compiler would provide the names Form1, Form2 etc. Each Form class created is a totally different class to any other because its characteristics have altered by the programmer (or VB) providing a unique name. When we start to add controls to the form the characteristics of the class will change even further from the original template provided by VB. © Peter Bilbie 2011-12 Page 14 of 24 To view some of the code provided by the compiler when we create a new class, click on Project->Add Windows Form and click Add in the following window – leave the name as default i.e. Form1. The form will be displayed with the Text Property set to Form1 – see below Double-click on the form to display the forms code window – see below: © Peter Bilbie 2011-12 Page 15 of 24 The code window displays the Class Template. However, this is not the only code to be provided by the VB environment. In the Solution Explorer click on the Show All Files icon – see below: The folder list in the Solution Explorer will show hidden files. Click on the icon next to the Form1 folder to open up the list – see below: Double-click on the Form1.Designer.vb and a different code window appears in the Design window – see below: © Peter Bilbie 2011-12 Page 16 of 24 Much of the code will be gobbledegook but you can see that it a Partial Class. This is because this code is part of the initialisation process for Form1 but it is usually hidden from the developer as it is very rare for programmers to want to change any of this pre-written code. Notice the line beneath the Partial Class declaration: Partial Class Form1 Inherits System.Windows.Forms.Form This states that the Form1 class inherits from a class named Form which can be located in a Class Library named Forms which is itself located in the Windows Library which is located in the System Library. This is known as a hierarchical reference similar to mapping folders in windows systems i.e. C:\My Documents\Pete The differwnce here is that we use the dot notation to map. Notice also the references to Me which is a reference to the form itself i.e. Form1. The code is using the dot notation to set certain Properties that have been inherited. For example, the lines below refer to the Name and Text properties of the Form: Me.Name = "Form1" Me.Text = "Form1" When we add controls to the form the compiler automatically creates objects of the control classes. Yes all controls i.e. textboxes, listboxes, comboboxes, labels etc are created from pre-defined classes. These pre-defined classes are contained in varios libraries. Open the frmCosyCottages.Designer.vb folder. Notice all the extra code in the window compared to the Form1 Designer window. In the Private Sub InitializeComponent you can see references to the controls that were added i.e. txtForename etc – see below for a sample. Private Sub InitializeComponent() Me.txtForename = New System.Windows.Forms.TextBox() Me.txtSurname = New System.Windows.Forms.TextBox() Me.txtAddress = New System.Windows.Forms.TextBox() What is happening is that the textbox controls that are on the Form (Me.) are being instantiated as objects of the class TextBox which can be located in the Systems.Windows.Forms library. Instantiated means an object of a class is being created – an instance (object) of a class is being created. Whenever an object is created the New method is always used. © Peter Bilbie 2011-12 Page 17 of 24 If you scroll down further in the code you can see where some of the new ojects properties are being set i.e. the Name property of the textbox txtSurname is assigned the string value “txtSurname” Me.txtSurname.Name = "txtSurname" More on the subject of OO concepts are covered in more detail in later sessions. Make sure you close the Designer windows and collapse the folder in the Solution Explorer by clicking on the Show All Files icon – we don’t want to inadvertently change any of the pre-written designer code as it may prevent the program from executing how it should. This is why they are hidden!! Displaying Images in PictureBoxes OK, back to the PictureBox image problem. To display images in the PictureBox you will need the following code: picCottage.Image = Image.FromFile("PetesPlace.jpg") Add the code above to the frmCosyCottage_Load Event – see below: Private Sub frmCosyCottages_Load(ByVal… lstCottage.Items.Add("Pete's Place") lstCottage.Items.Add("Winkers Rest") lstCottage.Items.Add("Bolt Hole") lstCottage.Items.Add("Fishy") lstCottage.Items.Add("Haven") lstCottage.Items.Add("Juanita") lstCottage.Items.Add("Parkstone") lstCottage.Items.Add("Sheila's Shack") lstCottage.Items.Add("The Grimley's") lstCottage.Items.Add("Vickies") lstCottage.Items.Add("Pete's Place") picCottage.Image = Image.FromFile("PetesPlace.jpg") End Sub Run the program and see the effect – it should look as below: © Peter Bilbie 2011-12 Page 18 of 24 Notice that the image does not fill the PictureBox. You will need to change the SizeMode property to StretchImage – see below: Re-run the program. However, we want the cottage that is selected in the listbox (lstCottage) to be displayed in the PictureBox (picCottage). To make this connection we need to look at some of the properties and Events of the listbox (lstCottage). © Peter Bilbie 2011-12 Page 19 of 24 When the program is running, if you click on an item in the list box the listboxes SelectedIndexChanged event is invoked. If there is no code in the event, nothing will happen. To access the SelectedIndexChanged event, double click on the listbox in design mode and the code window for the event will be displayed. This is because the SelectedIndexChanged is the default event for listboxes. A property of the listbox is its SelectedIndex which will return the index of the item selected. To see this in action, in the SelectedIndexChanged event of the listbox (lstCottage) we will assign the SelectedIndex value to the forename textboxes (txtForename) Text property i.e. Private Sub lstCottage_SelectedIndexChanged(ByVal… txtForename.Text = lstCottage.SelectedIndex End Sub Run the program and select an item in the listbox – a number should appear in the Forename textbox. Notice that if you click the first item in the list it returns 0 to the textbox. This is because all indexes in VB start at 0. Therefore, if you have 10 items in the list the last item will have an index of 9. What is needed now is to use the index to display the corresponding image in the picturebox. Add the following code to the SelectedIndexChanged event template of the listbox (lstCottage) Private Sub lstCottage_SelectedIndexChanged(ByVal… Dim i As Integer = lstCottage.SelectedIndex If i = 0 Then picCottage.Image = Image.FromFile("PetesPlace.jpg") ElseIf i = 1 Then picCottage.Image = Image.FromFile("WinkersRest.jpg") Else picCottage.Image = Nothing End If End Sub In the code above an integer variable (i) is declared and assigned the value returned by the lstCottage SelectedIndex. The ‘IF’ statement checks the value of ‘I’ and the code to display the corresponding image is invoked © Peter Bilbie 2011-12 Page 20 of 24 Exercise 1 The code for the SelectedIndexChanged only returns 2 of the images. Complete the code so that it displays the images of all cottages when selected. Completing the Program The only controls that do not have any functionality are the command buttons for Save, Print and Close buttons. For the purpose of this exercise we will only code the Save and Print buttons to display a message when clicked rather than saving or printing. The Close button will display a message that will ask the user if they are sure they want to close. Message Boxes Message boxes are used to inform the user of what is happening in applications, for example, ‘Document Sent to Printer’ or ‘Save before closing?’ To add messages to a command button, double-click on the button in the design window – this should take you to the Click Event of the button – see below The message box object has a Show method that takes a number of parameters. Each parameter is separated by a comma and the whole message and parameters are placed in brackets – see below Object Name Show method 1st parameter – The message to be displayed 2nd parameter – The Title of the message box MessageBox.Show("Your Work has been Saved", "Whoopee", MessageBoxButtons.OK, MessageBoxIcon.Information) 3rd parameter – The message type i.e. OK, Cancel etc © Peter Bilbie 2011-12 4th parameter – The message icon Page 21 of 24 The code above has been shown on two lines but in the program it was written on one line. It is possible to put code on more than one line by adding an underscore and a space and then pressing Enter – see below The message box that is displayed when you run the program and click the Save button is shown below – compare it with the code above. Code the Print button to show a suitable message In Messageboxes where there is a multiple choice i.e. Yes, No, Cancel the MessageBox can return a value depending on which button is clicked. This value can be used to code the response. Place the code below in the Close button: Private Sub btnClose_Click(ByVal… Dim response As Integer response = MessageBox.Show("Do you want to close?", "Close?", _ MessageBoxButtons.YesNoCancel, _ MessageBoxIcon.Question) If response = vbYes Then Me.Close() End If End Sub Notice that I have used underscores at the end of certain lines to allow displaying of code on multiple lines. In the code an integer variable (response) is declared. On the next line the value returned by the messagebox is assigned to the response integer variable. © Peter Bilbie 2011-12 Page 22 of 24 Yes returns the value 6 No returns the value 7 Cancel returns the value 2 Each of these values refers to Visual Basic Constants which are: vbYes – 6 vbNo – 7 vbCancel – 2 Therefore, is the user clicks ‘Yes’ then the code in the IF statement is invoked – Me.Close – and the form is close. Any other response and the messagebox is closed but the form stays open. Exercise 2 Provide suitable messageboxes and responses for the Save and Print buttons © Peter Bilbie 2011-12 Page 23 of 24 Summary During this session we have covered many concepts including: VB .NET as a Rapid Application Development Tool Controls – the toolbox and it’s contents Naming controls - conventions Creating an input form for a client - verification of system specification Classes and objects – Code Reuse Properties – setting properties using the Properties window and through code Methods – setting control methods and parameter passing Dot notation – accessing control methods and properties Events – coding controls from event procedures – event driven programming Intellisense – making coding easier and typo error free Message boxes – Informing the user We will cover many of the concepts above in more detail in later sessions © Peter Bilbie 2011-12 Page 24 of 24