1. Introduction The idea of the traditional programming

Size: px
Start display at page:

Download "1. Introduction The idea of the traditional programming"

Transcription

1 1. Introduction The way of programming differs a lot depending on a programmer using a traditional way of programming or if she/he uses a graphical environment for creating a program The idea of the traditional programming When writing programs in a traditional way it is common to write the user interface (input/output statements) in the same code as the statements performing the actual task. The program is one entity: it has one starting and one ending point. All what the program does is programmed between these two points. The program is deterministic in the sense that it starts from the starting point and follows deterministically up to the ending point. The user cannot take the control of the program flow. All the input and output is totally controlled by the program. An example of a traditional program is listed below: Sub Main() Dim Answer As String Dim Amount, Price, IncreasePercentage, TotalPrice As Integer Amount = InputBox("Enter amount") Do While Amount > 0 Price = InputBox("Enter price") TotalPrice = Amount * Price If TotalPrice > 100 Then TotalPrice = 0.9 * TotalPrice End If Answer = InputBox("Increase the price?") If Answer = "Y" Then IncreasePercentage = InputBox("How much:") TotalPrice = (1 + IncreasePercentage / 100) * TotalPrice End If MsgBox("The total price is " & TotalPrice) Amount = InputBox("Enter amount") Loop Lots of program statement has to be written in order to handle the conversation between the user and the application. The programmer has to write the whole logic of the interaction between the user and application.

2 1.2. The principle of the graphical development environment The idea of a graphical tool is to provide an easy to use tool to create the user interface by drawing it with mouse. The user works with a graphical interface consisting of forms, text boxes, labels etc. As a result, the user gets a ready made user interface (UI) for the application under development. The result is not only a static set of buttons, text boxes and other controls, but it includes the basic behaviour of these controls. The user is able to enter text into the text box, click the command buttons, etc. For instance:

3 The actions of the user with the interface are called events. Every event has a target control. Whenever the user does something important with the interface, for instance clicks a button, the interface notes that an event has taken place. For each important event, there must be a module (event procedure) that handles the event. When an event takes place, the interface fires that particular module (or event procedure) attached to the event. Graphical user interface (GUI) The user starts the execution of the code in the modules by causing events. Event Event Event Module 1 Module 2 Module How to develop applications using a graphical environment When developing applications in a graphical environment, the programmer develops the application by the following three steps: 1) Draw the user interface Drag and drop all the text boxes, command buttons, labels and other controls needed onto the form. Name each of the control on the form. Example:

4 2) Write the event procedures (modules) Module 1 Module 2 Sub btncalc_click() Handles btncalc.click 3) Link each event procedure (module) to a specific event of a control TextChanged MouseEnter Module 1 Module 2 Click Sub btncalc_click() Handles btncalc.click

5 1.4. The counterparts of controls in the memory Each control has its counterpart in the memory. For instance, text box txtamount has its contents in the memory. As a matter of fact, there is much of information about the text box among which the contents of the text box is named txtamount.text. Memory txtamount.text 5 When the user changes the contents of a text box, the value of the contents will also change in the memory, and vice versa. The text box on the form is actually a visual presentation of what the application has in the memory. Also the application can change values of a control in the memory. Example: The statement below will change the value of txtamount.text. The new value will be shown for the user on the UI. txtamount.text = 12 Memory txtamount.text 12

6 1.5. How the application works Memory txtamount.text 10 txtprice.text 45 txttotal.text Click Sub btncalc_click() Handles btncalc.click txttotal.text = txtamount.text * txtprice.text Memory txtamount.text 10 txtprice.text 45 txttotal.text 450 If txttotal.text > 100 Then txttotal.text = 0.9 * txttotal.text End If Memory txtamount.text 10 txtprice.text 45 txttotal.text 405

7 2. Graphical User Interface (GUI) A graphical windows environment consists of separate windows or forms. They contain different kinds of elements, such as text boxes, labels, pictures, buttons, scrollbars, menu items, list boxes, etc. These elements are called objects. They are like switches or turnings on a radio panel which the user uses to control the program. That's why they are also called controls Objects and properties Every object is of a specific object type. For example, in the picture below you can see four objects of type Label, four objects of type Text box, one object of type Picture box and three objects of type Command button. Each control (object) has a fixed number of properties, which represent the state of the particular control. For instance, Text boxes have properties like Name, Font, Text, Multiline, SelectedText, etc. Labels have properties Name, Font, Text, Image, etc. Every object type has the property Name. The names are used to identify the objects. That indicates that no two objects can share the same name.

8 Some common properties Every object type has a set of properties of its own. Some properties are common for different object types like those that determine the visual appearance: Font, Visible, etc. In the following table are listed some common properties and the object types which have these properties: Property Declaration Object BackColor BorderStyle Text Enabled Font.Name Font.Size Font.Bold Font.Italic Font.Underline... The background color used to display text and graphics in the controls Indicates whether or not the edit control should have a border. The object head line text or the text contents of the object Determines whether the user can use the control Determines how the font is like Almost all Label, PictureBox, TextBox Almost all Almost all Almost all Size The size of the control in pixels. Almost all Image A file name which contains the picture displayed on the face of the control. Button, Label, PictureBox SelectedText The selected text ComboBox, Text Box TabIndex The tab order of the control Almost all Tag Text associated with a control. Almost all Visible Determines whether the control is seen on the screen Almost all

9 Properties in the graphical environment In the graphical environment the list of the properties of the selected object is shown for the developer. So, it is possible to set values for the properties already at design time. Example:

10 Properties in the memory The visual objects have their counterparts in the computer's memory. They are implemented as a structure of property variables. The programs can set and change the property values at run time. For instance: Some of the property values for the objects in the following window could be as shown in the table below. Object type: Text Box Properties Name txtunits txtprice txtdiscount txttotal Text SelectedText 50 Font.Size Font.Bold False False False True Object type: Label Properties Name lblunits lblprice lbldiscount lbltotal Text Units Unit price Discount Total Font.Size Font.Bold False False False True Font.Italic False False True False Object type: Button Properties Name btncalcdiscount btncalctotal btnexit Text Calc Discount Calc Total Exit Font.Size 8,25 8,25 8,25 Font.Bold False False True

11 Referring to properties in program code When referring to the property values in the VB.NET code, one needs to write the name of an object and its specific property separated by a dot. ObjectName.PropertyName Example: Set 2 to the Text property value of the object with name txtunits. txtunits.text = Object as a control on the screen The end-user has direct access to some of the property values. When changing the text in the text box on the screen the text property value in the memory changes immediately. Memory txtunits.text 9 txtunits.selectedtext txtunits.font.size 12

12 2.2. Interactive environment: Events The user has all kinds of possibilities to input data and control the program execution. He or she can click a button using the mouse, change the value of a text box, press a key in a text box, get the focus onto the text box, etc. These actions are called events. When an event is triggered, it means that something happens to an object. Events have always an object as a target. Event Object Click For instance: Event Object Name Click btncalctot Leave btncalcdis Click txtunits Enter txtdiscount DoubleClick lblprice Event Procedures When an event occurs, the computer has to execute some program statements. These statements are written to special procedures called event procedures. Every event is associated to one event procedure. This procedure is executed each time the event occurs. When an event occurs, the system fires (calls) a procedure, that can be identified to be the correct one. The heading of event procedures end with the Handles keyword, which after is the name of the object and the name of the event separated by a dot. Sub Handles ObjectName.EventName Example: When clicking the btncalctot Button the system fires the following kind of procedure: Private Sub btncalctot_click( ) Handles btncalctot.click... Attention! The name of the procedure could be just anything, even though the common habit is to write it in the way shown in the example above.

13 One object can be a target of several events. The identification of the event procedure determines which event is fired at the time. For instance: Click TextChanged Sub ClickClack( ) Handles txtunits.click Sub TC( ) Handles txtunits.textchanged The events usually are actions made by the user. But, the events can also be triggered by other events. Example: If the user clicks a button and it fires a procedure that changes the Text property value of the object txtunits, then the TextChanged event is directed to the object txtunits as well. Click An end-user fires an event procedure Sub btncalctotal_click( ) Handles btncalctotal.click txtunits.text = 4 This statement triggers an event procedure as well! Sub TC( ) Handles txtunits.textchanged

14 Some of the most common events Event Declaration Object Activated When a form is activated Form Deactivate When a form is deactivated Form TextChanged When the text is changed Almost all Click When the control is clicked Almost all DoubleClick When the control is double clicked Almost all Enter When the focus is moved to the control Almost all KeyPress When a key is pressed within a control Almost all Leave When the control loses the focus Almost all 2.3. Methods Methods are sub procedures associated to an object. The methods have a specific task to do for the specific object. For instance, if we have a text box object named txttextbox, a method AppendText(parameter) appends the text given as a parameter, into this particular text box. Each object type has a set of methods of its own. To call a method in the VB.NET code one needs to write the name of an object and a name of one its method separated by a dot. ObjectName.MethodName(parameter1, parameter2, ) When referring to the property values in the VB.NET code, one needs to write the name of an object and its specific property separated by a dot. Example: First write text Hello into a text box named txttextbox. After that append text World! to the same text box. 1: txttextbox: 2: txttextbox.text = "Hello" txttextbox: 3: txttextbox.appendtext(" World!") txttextbox:

15 Some useful methods.setbounds(left as Integer, top as Integer, width as Integer, height as Integer) Moves the object to a new location (given the new coordinates of the left upper corner) and sets a new width and height for the control. Examples: 1. Move the object to a new location and set a new width for the control. btnexit.setbounds(1200, 600, 40, 20) 2. Move the text box 20 pixels down. txtedit.setbounds(txtedit.left, txtedit.top + 20,_ txtedit.width, txtedit.height).hide() Hides the control from the end-user..show() Shows the control to the user..copy() Copies the selected text in the control to the clipboard..cut() Cuts the selected text in the control to the clipboard..paste() Pastes the contents of the clipboard into the text of the control. Example: Copy the selected text of the TextBox1 into the TextBox2. TextBox1.Copy() TextBox2.Paste()

16 3. The most common controls 3.1. Form A form is a representation of any window displayed in an application Couple of properties Text The Text property allows you to specify the caption of the window in the title bar. FormBorderStyle The border style of the form determines how the outer edge of the form appears. In addition to changing the border display for a form, certain border styles prevent the form from being sized. Setting the FormBorderStyle property to FixedDialog changes the border of the form to that of a dialog box and prevents the form from being resized A useful event Load Occurs before a form is displayed for the first time. You can use this event to perform tasks such as allocating resources used by the form Label Use this control to display data on the screen. The text visible on the label control is the Text property value. The value of the Text property can not be changed by the end-user; it can be changed only programmatically. Private Sub lblcompanyname_mouseenter( ) Handles lblcompanyname.mouseenter lblcompanyname.text = "Company Ltd" Private Sub lblcompanyname_mouseleave( ) Handles lblcompanyname.mouseleave lblcompanyname.text = ""

17 3.3. TextBox Use this control for letting the user to enter text. The default value can be set at design time Useful properties Text The value entered into the text box is hold in the Text property. The data type of the property is String. If the value of the property is a number, it could be used as a numeric expression such as: txtunits.text * txtprice.text It may work, but it doesn t always. To ensure that no error occur the value needs to be converted to numeric values by using the Convert.ToDouble(), Convert.ToInt32(), ConvertToDecimal(), etc. functions. So, the right way to multiply two values of the Text properties of some text boxes would be as follows: Convert.ToDouble(txtUnits.Text) * Convert.ToDouble(txtPrice.Text) The following logical functions are an easy way to test the type of the Text property value: IsNumeric(txtTextBox.Text) Return value: True - numeric value False - non numeric value IsDate(txtTextBox.Text) Return value: True - date value False - non date value SelectedText Contains the part of the text, which has been selected by the end-user. In the case above the value of the SelectedText property would be real. Enabled Logical, True if the user can enter the Text and change the Text property value, False if not

18 MultiLine Logical, True if the text box can contain several lines False if the text box contains only one line Visible Logical, True if the control is visible on the form, False if not Events TextChanged Occurs when the content of the text box is changed DoubleClick Occurs when the control is double-clicked Private Sub RightAlign( ) Handles txttextbox.doubleclick txttextbox.textalign = HorizontalAlignment.Right Enter Leave Occurs just before the object gets the focus. Occurs immediately after leaving the control. Private Sub txttextbox_leave( ) Handles txttextbox.leave If IsNumeric(txtTextBox.Text) Then End If KeyPress Occurs when a key is pressed while the control has focus. Using this event handler, every key pressed by the user can be checked. The value of the key pressed is hold in the property e.keychar. Private Sub txttextbox_keypress(, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles txttextbox.keypress If Char.IsNumber(e.KeyChar) Then MessageBox.Show("The key pressed is numeric!") ElseIf Char.IsControl(e.KeyChar) Then MessageBox.Show( _ "The key pressed is a control character!") End If A useful method Clear Clears all text from the text box control. It can be used to clear the contents of the control instead of assigning the Text property an empty string.

19 3.4. Button Use this control to start a task chosen by the user. It is mostly used together with the Click event. For instance: Private Sub btncalctotal_click( ) Handles btncalctotal.click txttotal.text = Convert.ToDouble(txtUnits.Text) * _ Convert.ToDouble(txtPrice.Text) 3.5. PictureBox This control is used to show bitmaps on the screen. The property Image is used to contain the file name which contains the picture that the picture box displays. Private Sub pixpicturebox_click( ) Handles pixpicturebox.click pixpicturebox.image = Image.FromFile("C:/pics/MyHouse.bmp")

20 4. Other common controls 4.1. GroupBox A group box is used for logically grouping controls on a form. The GroupBox displays a frame around a group of controls with or without a caption. Note Only controls contained within a group box can be selected or receive focus. The entire group box itself cannot be selected or receive focus. Example: Setting the Visible property value to false makes the group box and all the controls inside it invisible for the end-user. Respectively, the Enabled property can be set to False, if the user is allowed to see the controls but not to access them. grxgroupbox.visible = False grxgroupbox.enabled = False 4.2. RadioButton A radio button is used for letting the user to choose one out of a few given choices. The property Checked indicates the selection. For instance: If rbnmarried.checked = True Then 'Married End If

21 When the user selects one radio button within a group (e.g. controls Form, TabControl, GroupBox, and Panel), the others clear automatically. All RadioButton controls in a certain container, such as a Form, constitute a group. To create multiple groups on one form, each logical group needs to be placed in its own container, such as a GroupBox control CheckBox The CheckBox control is similar to the RadioButton control: They both allow the user to choose from a list of options. The difference is that check boxes let the user pick a combination of options. In contrast, radio buttons allow a user to choose from mutually exclusive options. As well as the RadioButton control, the CheckBox control has the Checked property for indicating weather the user has checked the check box in question ScrollBar A ScrollBar control is used to implement a scrolling effect. It can be used for example for user input of numeric data. A ScrollBar control can be selected either to be an HScrollBar or a VScrollBar control. The letters H and V stand for horizontal and vertical.

22 A few essential properties Minimum The Minimum property value indicates the minimum value, which the user can select. Maximum The Maximum property value indicates the maximum value, which the user can select. Value The Value property holds the current value of the scrollbar and thereby indicates the position of the scroll box within the scrollbar. SmallChange The SmallChange property determines the distance the scroll box moves when the user clicks the scroll arrows at each end of the control. LargeChange The LargeChange property determines the distance the scroll box moves when the user clicks within the scroll bar but outside the scroll box and the scroll arrows An useful event ValueChanged Occurs when the Value property has changed. Example: Let the user enter the temperature between -30 and +40 degrees. Private Sub hsrtemperature_valuechanged( ) Handles hsrtemperature.valuechanged lbltemperature.text = hsrtemperature.value

23 5. More Controls 5.1. TrackBar The TrackBar is a scrollable control similar to the ScrollBar control. You can configure ranges through which the value of the Value property of a track bar scrolls by setting the Minimum property to specify the lower end of the range and the Maximum property to specify the upper end of the range. The LargeChange property defines the increment to add or subtract from the Value property when clicks occur on either side of the slider. The track bar can be displayed horizontally or vertically by setting the Orientation property to Horizontal or Vertical ProgressBar A ProgressBar control visually indicates the progress of a lengthy operation. The ProgressBar control displays a bar that fills in from left to right with the system highlight color as an operation progresses. Users of an application might consider an application unresponsive if there is no visual cue. The Maximum and Minimum properties define the range of values to represent the progress of a task. The Minimum property is typically set to a value of zero, and the Maximum property is typically set to a value indicating the completion of a task. The Value property represents the progress that the application has made toward completing the operation. The value displayed by the ProgressBar can be modified in different ways: 1. To change the Value property directly. ProgressBar1.Value += 5 2. To use the Step property to specify a specific value to increment the Value property by, and then call the PerformStep method to increment the value. ProgressBar1.Step = 5 ProgressBar1.PerformStep() 3. To use the Increment method. It takes the amount by which to increment the Value property as its argument and then increments the value. ProgressBar1.Increment(5)

24 5.3. Timer The Timer control is like a metronome that ticks at a regular interval by raising the Timer Tick event. The frequency of the Tick event calls is set in the Interval property of the timer. It can be set both at design time and programmatically. The value of the interval is in milliseconds. Example: The program is a timer for showing the time in seconds. It starts when the user clicks the Start button and ends when the user clicks the Stop button. The interval is set at design time. The code would look as follows: Private Sub btnstart_click( ) Handles btnstart.click Timer1.Start() Private Sub btnstop_click( ) Handles btnstop.click Timer1.Stop() lbltime.text = 0 Private Sub Timer1_Tick( ) Handles Timer1.Tick lbltime.text += 1

25 5.4. MenuStrip The MenuStrip control represents the container for the menu structure of a form. A menu is composed of MenuItem objects that represent the individual menu commands in the menu structure. Each MenuItem can be a command for the application or a parent menu for other submenu items. The ShortcutKeys property can be used to define a keyboard combination that can be pressed to select a menu item. The menu items can also have access keys for selecting them by using a specified letter key when a menu is open. A helpful event Click Occurs when the MenuItem is clicked by the user. This event also occurs if the user selects the menu item using the keyboard and presses the Enter key. It can also occur if an access key or shortcut key is pressed that is associated with the MenuItem. Example: Add a shortcut Ctrl+O and an access key (O) to the Open menu item. When the user selects the Open menu item, the message shall appear to her/him. 1. Selecting the menu item from the File menu with mouse or using arrow keys 2. Using the shortcut key Ctrl+O 3. Pressing key O when the File menu is open Private Sub mnuopen_click( ) Handles mnuopen.click MessageBox.Show("You clicked the Open menu", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Information)

26 5.5. MessageBox In the previous example a message box was opened to inform the user from clicking the menu item. In addition to just giving information, the message boxes may be applied to get feedback from the user when a decision has to be made about the next program path to be selected. With the method MessageBox.Show() the following properties can be set for the appearing message box. The values for the properties are given with the corresponding parameters when calling the method. messageboxtext caption button icon Text, which appears in the message box body. The only obligatory parameter. Text appearing in the message box header, optional. The selection of the buttons to be shown in the message box. The available values for the parameter are: MessageBoxButtons.OK Show only OK button MessageBoxButtons.OKCancel Show OK and Cancel buttons MessageBoxButtons.YesNoCancel Show Yes, No and Cancel buttons MessageBoxButtons.YesNo Show Yes and No buttons The selection of the icon to be shown in the message box. The available values for the parameter are: MessageBoxIcon.None MessageBoxIcon.Hand MessageBoxIcon.Question MessageBoxIcon.Exclamation MessageBoxIcon.Asterisk MessageBoxIcon.Stop MessageBoxIcon.Error MessageBoxIcon.Warning MessageBoxIcon.Information defaultresult The default value to be returned to the calling code The value returned by the MessageBox after a message box button has been pressed can be one of the following: None No result returned OK OK button pressed Cancel Cancel button pressed Yes Yes button pressed No No button pressed

27 Example: Call a message box with Yes and No buttons and a warning icon. If Yes button is pressed, the program is continued, otherwise terminate the program. Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click If MessageBox.Show("Should we continue", "Warning", _ MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = _ Windows.Forms.DialogResult.No Then Me.Close() End If

28 6. One more important control 6.1. ListBox The ListBox control enables displaying a list of items to the user that the user can select by clicking. A list box is like a text string array on the screen. Each item has an index and content. The indexes of the items are zero-based (start from zero). Example: In the list box below the indexes of the items are as follows: Index Items 0 Chair 1 Shelves 2 Sofa 3 Desk The index of the selected item is 2. The control stores the index of the currently selected item in the property called SelectedIndex. So, the statement: MessageBox.Show("Selected index: " & lbxfurniture.selectedindex) would cause displaying of the following kind of message box: Items property The Items property of the ListBox control stores the items displayed in the list box. It s data type is a collection. (Collections are similar to arrays; they will be discussed later in detail.) This property gives the programmer a reference to the list of items that are currently stored in the list box (see the Example above). With this reference it s possible to get and set items, add items, remove items, and obtain a count of the items in the collection.

29 Example: In the following program the user can select an item from the list box lbxfurniture and the program copies the selected item into the text box named txtselectedfurniture. If lbxfurniture.selectedindex = -1 Then MessageBox.Show("Select the item first") Else txtselectedfurniture.text = _ lbxfurniture.items(lbxfurniture.selectedindex) End If Basic properties Item Count Gets or sets the item at the specified index within the collection. For instance: lbxfurniture.items.item(2) = "Sofa" The number of items in the collection Useful methods IndexOf The method returns the zero-based index where the item is located within the collection. If the item does not exist, the return value is negative one (-1). In the situation shown above, the return value of the statement lbxfurniture.items.indexof("chair") would be 0. Add Adds an item to the list of items for a list box and returns the index of the item in the collection. If the Sorted property of the ListBox control is set to true (the default value is false), the item is inserted into the list alphabetically. Otherwise, the item is inserted at the end of the list. For instance: Dim indexofaddeditem As Integer indexofaddeditem = lbxfurniture.items.add("table")

30 RemoveAt This method removes the item at the specified index within the list box. Note: When an item is removed from the list, the indexes change for subsequent items in the list. Example: The program below shows the index of the item Table before and after removing the 3rd item of the list box. MessageBox.Show("Index of item 'Table' is now: " & _ lbxfurniture.items.indexof("table")) lbxfurniture.items.removeat(2) MessageBox.Show("Index of item 'Table' is now: " & _ lbxfurniture.items.indexof("table")) Clear Removes all items from the Items collection. lbxfurniture.items.clear()

31 Summary To give an overview, in the following example there are collected some of the properties and methods and their values, which are discussed above. Example: lbxfurniture.selectedindex (value 2) lbxfurniture.selecteditem (value Sofa ) lbxfurniture.items.item(lbxfurniture.selectedindex) (value Sofa ) lbxfurniture.items.item(1) (value Shelves ) lbxfurniture.items.count() (value 4) lbxfurniture.items.indexof("desk") (value 3)

32 7. Variables and constants 7.1. Variables A variable is a temporary location for the data in a program. It has a name and a memory address and it is of one data type. The data type determines the possible values that the variable can assume Data types There are two fundamental categories of data types in Visual Basic.NET: value types and reference types. The value types hold in their memory address the actual data. In contrast, the reference types point to the data, which is actually located elsewhere in the memory. All the other types are reference types except for the numeric types. Visual Basic type Nominal storage allocation Value range Boolean 2 bytes True or False. Byte 1 byte 0 through 255 (unsigned). Char 2 bytes 0 through (unsigned). Short 2 bytes through Integer 4 bytes through Long (long integer) Single (single-precision floating-point) Double (double-precision floating-point) 8 bytes through bytes E+38 through -+1.4E-45 8 bytes E+308 through E-324. Decimal 16 bytes 0 through +/ String Depends on 0 to approximately 2 billion Unicode characters. (variable-length) implementing platform DateTime 8 bytes 0:00:00 on January 1, 0001 through 11:59:59 PM on December 31, Object 4 bytes Any type can be stored in a variable of type Object. User-Defined Type (structure) Depends on implementing platform Each member of the structure has a range determined by its data type and independent of the ranges of the other members.

33 Variable declaration Dim VariableName As Type Dim VariableName1, VariableName2 As Type Dim icountofordered As Integer Dim strfirstname, strlastname As String Private Sub btncalcdisc_click( ) Handles btncalcdisc.click 'Write data declarations Dim idiscount As Integer idiscount = Data type conversion The assignments have to be done in between same data types: string (text) values must be converted to numeric in numeric expressions and numeric values to strings in string expressions. Use Convert class s methods (ToDouble, ToString, ToInt32, etc.) for doing that. The most common way to use the Convert class is to do the type conversion between a numeric value and a string. Type conversion: Numeric String Convert.ToDouble(StringValue) Convert.ToString(NumericValue) For instance: MessageBox.Show("Your discount is " & Convert.ToString(iDiscount)) txttotal.text = Convert.ToString(dPi) txttotal.text = Convert.ToString(Convert.ToDouble(txtUnits.Text) * _ Convert.ToDouble(txtPrice.Text))

34 Date Variables A date uses DateTime data type, which is a 64-bit integer value. It represents dates and times with values ranging from 00:00:00 midnight, January 1, 0001 to 23:59:59, December 31, Dim MyDate1, MyDate2, MyDate3 As DateTime MyDate1 = Convert.ToDateTime(" :00") MyDate2 = MyDate1.AddDays(14) MyDate3 = DateTime.Now() The current system date and time The DateTime class has properties to get the DateTime that is the current local date and time on this computer. The current date: DateTime.Today DateTime.Now.Date The current time: DateTime.Now.ToShortTimeString() 15:12 DateTime.Now.ToLongTimeString() 15:12: Constants Constants are values that have a name. The Const statement is used to declare a constant and set its value. Once a constant is declared, it cannot be modified or assigned a new value. A constant can be declared with or without a type statement. Const ConstantName = Value Const ConstantName As Type = Value Const Pii = Const CompanyName = "Company Ltd" Const Pii As Double = Constants can be used just like variables, but their values cannot be changed.

35 MessageBoxButtons constants You can specify with the MessageBoxButtons constants, what buttons are displayed on the message box. For instance: MessageBox.Show("Message text", "Caption", MessageBoxButtons.OKCancel) Member name AbortRetryIgnore OK OKCancel RetryCancel YesNo YesNoCancel Description The message box contains Abort, Retry, and Ignore buttons. The message box contains an OK button. The message box contains OK and Cancel buttons. The message box contains Retry and Cancel buttons. The message box contains Yes and No buttons. The message box contains Yes, No, and Cancel buttons MessageBoxIcon constants You can specify with the MessageBoxIcon constants, what icon is displayed on the message box. MessageBox.Show("Message text", "Caption", MessageBoxButtons.RetryCancel, _ MessageBoxIcon.Question)

36 Member name Asterisk Error Exclamation Hand Information None Question Stop Warning Description The message box contains a symbol consisting of a lowercase letter i in a circle. The message box contains a symbol consisting of white X in a circle with a red background. The message box contains a symbol consisting of an exclamation point in a triangle with a yellow background. The message box contains a symbol consisting of a white X in a circle with a red background. The message box contains a symbol consisting of a lowercase letter i in a circle. The message box contains no symbols. The message box contains a symbol consisting of a question mark in a circle. The message box contains a symbol consisting of white X in a circle with a red background. The message box contains a symbol consisting of an exclamation-point in a triangle with a yellow background DialogResult constants DialogResult constants are the identifiers to indicate the return value of a dialog box. For instance: Dim Result As DialogResult Result = MessageBox.Show("Message text", "Caption", _ MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) If Result = DialogResult.Cancel Then 'The user clicked Cancel Else End If

37 Member name Abort Cancel Ignore No None OK Retry Yes Description The dialog box return value is Abort (usually sent from a button labeled Abort). The dialog box return value is Cancel (usually sent from a button labeled Cancel). The dialog box return value is Ignore (usually sent from a button labeled Ignore). The dialog box return value is No (usually sent from a button labeled No). Nothing is returned from the dialog box. This means that the modal dialog continues running. The dialog box return value is OK (usually sent from a button labeled OK). The dialog boxs return value is Retry (usually sent from a button labeled Retry). The dialog boxs return value is Yes (usually sent from a button labeled Yes) The control character constants The control character constants are used for handling special characters. Example: Append to a textbox some text, tabular and a numeric value with a new line character. txtoutputarea.appendtext("total sum" & ControlChars.Tab & dsum & _ ControlChars.NewLine) Member name Equivalent Description CrLf Chr(13) + Chr(10) Carriage return/linefeed character combination. Cr Chr(13) Carriage return character. Lf Chr(10) Linefeed character. NewLine Chr(13) + Chr(10) New line character. NullChar Chr(0) Character having value 0. Tab Chr(9) Tab character. Back Chr(8) Backspace character.

38 Key codes (numeric codes representing the key pressed) The constants of keys (key codes) are used for processing keyboard input. Example: Private Sub txttextbox_keydown(, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles txttextbox.keydown If e.keycode = Keys.F3 Then MessageBox.Show("F3 was pressed") End If Button Key code Cancel System.Windows.Forms.Keys.Cancel System.Windows.Forms.Keys.Back System.Windows.Forms.Keys.Tab (Tab) System.Windows.Forms.Keys.Return A (65) System.Windows.Forms.Keys.A B (66) System.Windows.Forms.Keys.B 0 (48) System.Windows.Forms.Keys.D0 1 (49) System.Windows.Forms.Keys.D1 F1 (112) System.Windows.Forms.Keys.F1 F2 (113) System.Windows.Forms.Keys.F2

39 8. Procedures A procedure is a block of code which has got an individual name and can be called from other places in the program. To get the desired result, data can be passed as parameters to the procedure when calling it. These parameters are placed within parentheses after the name of the procedure to be called. MyProcedure(parameter1, parameter2) There are two ways of passing the data: by value (keyword ByVal) and by reference (keyword ByRef). By default the parameters are passed by value. It means that in the procedure a local variable is assigned a value of a parameter. Changes on the value of the local variable inside the procedure can t be seen outside of it. When defining the input parameter as reference, the local variable is simply a reference to the parameter being passed. In that case all changes made to the local variable inside the procedure will also be reflected in the calling parameter and can be seen outside the procedure. The definition of the type of the parameter passed is done in the procedure definition. Sub MyProcedure(ByVal parameter1 As Integer, ByRef parameter2 As Double) There are two kinds of procedures: subroutines (keyword Sub) and functions (keyword Function). The functions return a value whereas subroutines don t Sub routine procedures General procedures are sub programs that other procedures of the same application can call. The syntax of the sub routine call is like any statement. You have to write the name of the procedure followed by the parameters in parentheses. Example: 1. Private Sub btncalcdisc_click( ) Handles btncalcdisc.click Dim ipercent, iunits As Integer Dim dprice As Double ipercent = 10 dprice = Convert.ToDouble(txtPrice.Text) iunits = Convert.ToInt32(txtUnits.Text) ShowDiscount(iPercent, dprice, iunits) Sub ShowDiscount(ByVal percent As Integer, _ ByVal price As Double, _ ByVal units As Integer) Dim idiscountpercent As Integer Dim ddiscount As Double If units > 1000 Then idiscountpercent = percent + 10 Else idiscountpercent = percent End If ddiscount = idiscountpercent / 100 * price * units MessageBox.Show("Discount is: " & ddiscount)

40 2. Private Sub btncalcdisc_click( ) Handles btncalcdisc.click Dim ipercent, iunits As Integer Dim dprice, ddiscount As Double ipercent = 10 dprice = Convert.ToDouble(txtPrice.Text) iunits = Convert.ToInt32(txtUnits.Text) CountDiscount(iPercent, dprice, iunits, ddiscount) txtdiscount.text = Convert.ToString(dDiscount) Sub CountDiscount(ByVal percent As Integer, ByVal price As Double, _ ByVal units As Integer, ByRef discount As Double) Dim idiscountpercent As Integer If units > 1000 Then idiscountpercent = percent + 10 Else idiscountpercent = percent End If discount = idiscountpercent / 100 * price * units 8.2. Function procedures Functions are like sub procedures but they return a value to the calling procedure. The data type of the value, which a function procedure returns, is the data type of the function. The value is returned by a Return statement or the returned value can be assigned to the value of a variable with the name of the function. The following examples explain how to write the procedure shown above, as a function procedure. Example: Private Sub btncalcdisc_click( ) Handles btncalcdisc.click Dim ipercent, iunits As Integer Dim dprice, ddiscount As Double ipercent = 10 dprice = Convert.ToDouble(txtPrice.Text) iunits = Convert.ToInt32(txtUnits.Text) ddiscount = CountDiscount(iPercent, dprice, iunits) txtdiscount.text = Convert.ToString(dDiscount)

41 Function CountDiscount(ByVal percent As Integer, ByVal price As Double, _ ByVal units As Integer) As Double Dim idiscountpercent As Integer If units > 1000 Then idiscountpercent = percent + 10 Else idiscountpercent = percent End If Return idiscountpercent / 100 * price * units End Function The function CountDiscount could also be written as follows without the Return statement: Function CountDiscount(ByVal percent As Integer, ByVal price As Double, _ ByVal units As Integer) As Double If units > 1000 Then CountDiscount = percent + 10 Else CountDiscount = percent End If CountDiscount = CountDiscount / 100 * price * units End Function 8.3. Event procedures An event procedure is a block of code that is executed when an object is manipulated in a program. An event that triggers the event procedure can be user-generated. For example, when a Button object is clicked, the Button_Click event procedure is executed. An event can also be system generated, such as the Load event of a form, or it can be a custom event that you define in your code. A procedure is associated to an event with the keyword Handles followed by the control name and the keyword of the event. Event procedures can be called explicitly from the code just as any other procedures. Example: 1) A user-generated event (clicking btncalcdisc button on the form) triggers the execution of the event procedure that handles the btncalcdisc s Click event: Sub btncalc_click( ) Handles btncalcdisc.click 2) Event procedures can be called explicitly: Sub DoSomething() btncalc_click( )

42 9. Scope of variables and procedures Variables (and constants) and procedures have a scope, which indicates where in the program the variable or the procedure is visible to the code; that is, where it can be referred to in the code. There are four kinds of scopes: 1. code blocks, 2. procedures, 3. modules and 4. namespaces Code block-level scope When declaring a variable within a code block (i.e. a set of statements that is terminated by an End, a Loop or a Next statement) the variable is visible only within that block. Example: Defining a variable inside an If block prevents the variable from being seen outside the block. If units > 1000 Then Dim idiscountpercent As Integer idiscountpercent = percent + 10 Else idiscountpercent = percent End If Return idiscountpercent / 100 * price * units error scope of the variable idiscountpercent 9.2. Procedure-level scope When declaring a variable within a procedure but outside a code block, the variable is seen in the procedure in which it is declared. Would we declare a variable with the same name in two separate procedures, the program would work as intended: the variables with the same name would be two different variables. On the other hand we can t refer to a variable, which is declared in another procedure: Sub DisplayNumberFour() Dim number, i As Short number = 4 MessageBox.Show(Convert.ToString(number)) These are different Sub DisplayNumberTen() variables Dim number As Short i = 50 error number = 10 MessageBox.Show(Convert.ToString(number)) scope of the variables number and i scope of the other variable number

43 9.3. Module-level scope A module in VB programs is a basic building block: a Class (as a Form is), a Module, or a Structure. Variables and procedures can be declared at this level by placing the declaration statements outside of any procedure or block but within a class, module, or structure. The variables and procedures declared in the module-level can be referred to from all the procedures in the same module. Example: scope of the variables A, B and the procedures DoSomething and btnbutton_click scope of the variable C Public Class Form1 Dim A As Integer Dim B As Integer '#1 '#2 Sub DoSomething() '#4 B = A + 10 'Refers to variables #2 and #1 Private Sub btnbutton_click(...) Handles btnbutton.click Dim C As Integer '#3 C = A + 1 'Refers to variables #3 and #1 DoSomething() 'You can also call procedures (#4) 'of the same form. End Class 9.4. Namespace-level scope A namespace is an abstract container for holding a logical grouping of unique names (e.g. variable or procedure names). Namespaces may be created in VB with the Namespace statement. If a project doesn t contain any Namespace statements, everything in the project is in the same namespace. In this case, namespace-level scope can be thought of as project-level scope. If an element (e.g. a variable or a procedure) is declared in a module-level scope with the Friend or Public keyword, it becomes available to all procedures throughout the namespace in which the element is declared. So, if there s no namespaces declared explicitly, the elements can be referred to from all modules in the project. Keyword Private can be used for explicitly hiding the elements from other modules. Variables declared with the keyword Dim have the same scope as if they would have been declared with the keyword Private.

44 Example: Code module: Module1.vb Module Module1 Public K As Integer Dim A As Integer '#1 '#2 Public Sub Procedure1() Dim B As Double '#3 '#4 B = K + A 'Refers to variables #4, #1 and #2 Private Sub Procedure2() End Module Dim B As Double '#5 '#6 B = K + A 'Refers to variables #6, #1 and #2 Procedure1() 'Refers to procedure #3 Code module: Module2.vb Module Module2 Dim A As Integer '#7 Private Sub Procedure3() Dim B As Double '#8 '#8 B = K + A 'Refers to variables #9, #1 and #7 Procedure1() 'Refers to public procedure #3 'in code module Module1.vb Procedure2() error End Module

45 9.5. Same variable name in several levels Sometimes the same variable name may appear in different places of the code assigned to different actual variables. This may happen if the code is written by several programmers or if code written for a different project is being reused in a new project. The VB compiler can sometimes handle these cases but quite often the programmer has to explicitly tell the compiler which variable to use. The compiler selects the variable scope which is closest to the variable call if it is feasible. Two variables with the same name may be defined in both module level and in procedure level. In this case the variable used in the procedure is the one defined inside the procedure. If especially the variable defined in the module level is wished to be used inside a procedure where a variable with the same name exists, the name of the variable has to be written with the module level name. In case the module is a class or a structure the module level name is Me. In case the module level is a type of Module, the corresponding level name is the name of the module. The same variable name cannot however be defined both in a procedure-level and in a blocklevel of the same procedure. Example: Module module1 Dim beta As Integer valid definitions Sub DoSomething() Dim alfa As Integer For i As Integer = 1 To 90 Dim alfa As Integer Dim beta As Double alfa = 32 Next For j As Integer = 1 To 90 Dim beta As Double alfa = 32 beta = 43 + module1.beta Next End Module valid call to the block level variable second definition is not valid valid call to the module level variable

46 10. What is an object? An object is a representation of a thing that is manipulated in the application. The manipulation of an object happens through its properties and methods. Properties are things that describe features of an object. Programmatically they are data fields (variables) that hold the data values. For example, if having an object car, it would have properties model, colour, max speed, etc. Methods are ways of instructing an object to do something. Programmatically they are procedures, which perform an action for the object. For example, the object car could have methods like speed up, get fuel, turn, etc Properties Object a: Object b: Object c: Name YearOfBirth Name YearOfBirth Model LicensePlate Speed Referring to properties in program code ObjectName.PropertyName a.name = "John" Object a: Name YearOfBirth results: John c.speed = 80 Object c: results: Model LicensePlate Speed 80 c.speed = c.speed + 10 Object c: Model LicensePlate Speed 90 results:

47 Definition of properties The properties of an object are defined in the object class. An object class can be thought as blueprint of a house. Whereas the objects can be thought as houses build according to that blueprint. Class Person Name YearOfBirth Class Car Model LicensePlate Speed In program code: Public Class Person Public Name As String Public YearOfBirth As Integer End Class Public Class Car Public Model As String Public LicensePlate As String Public Speed As Integer End Class Creating objects Each object is a member of an object class. The class defines the properties and methods that are adopted by all it s members. When creating an object it is given a variable name and the name of the object class according to which it will be built. Class Person Name YearOfBirth Class Car Model LicensePlate Speed a b c In program code: Dim a As Person Dim b As Person Dim c As Car

48 An object variable defines a name for the object, but not the object itself (memory space). The keyword New is used to create the object (defining memory space and initializing the properties). The object can be created in an assignment statement 'Defining object names Dim a As Person Dim b As Person Dim c As Car 'Defining memory area for the objects a = New Person() b = New Person() c = New Car() or in the dim statement: 'Defining both object names and memory area for the objects Dim a As New Person() Dim b As New Person() Dim c As New Car() Class Person Name YearOfBirth Class Car Model LicensePlate Speed a b c Name YearOfBirth Name YearOfBirth Model LicensePlate Speed

49 Objects are actually implemented as links (pointers, memory addresses) to the actual memory area of the object. Object variable a: Address of object a Memory area for object a: a.name a.yearofbirth Name YearOfBirth The value of the object variable is a link to the actual object. The link can be changed to point to another object of the same kind. a: b: Name Jack YearOfBirth 1981 Name Lisa YearOfBirth 1979 The assignment a = b a: b: Name Jack YearOfBirth 1981 Name Lisa YearOfBirth 1979

50 Example: The following program creates two objects of class Person, one for a female and one for a male person. The Set button sets the property values and the Show button shows the values. Public Class Person Public Name As String Public YearOfBirth As Integer End Class Public Class Form1 Inherits System.Windows.Forms.Form Dim female As New Person() Dim male As New Person() Private Sub btnset_click( ) Handles btnset.click If rbnfemale.checked = True Then female.name = txtname.text female.yearofbirth = Convert.ToInt32(txtYearOfBirth.Text) Else male.name = txtname.text male.yearofbirth = Convert.ToInt32(txtYearOfBirth.Text) End If Private Sub btnshow_click( ) Handles btnshow.click If rbnfemale.checked = True Then txtname.text = female.name txtyearofbirth.text = female.yearofbirth Else txtname.text = male.name txtyearofbirth.text = male.yearofbirth End If End Class

51 11. Combining objects Objects can be used the same way as any other data type. They can be used as elements of an array as well as a type of a property of another object. The other way around, objects can contain arrays and other objects as they contain any other type of data Objects in arrays Objects can be placed in arrays. Public Class Person Public Name As String Public YearOfBirth As Integer End Class Dim Personnel(4) As Person Create an object for each element: Dim i As Integer For i = 0 To 4 Personnel(i) = New Person() Next Name Name Name Name Name YearOfBirth YearOfBirth YearOfBirth YearOfBirth YearOfBirth Ask the names and ages: Dim i As Integer For i = 0 To 4 Personnel(i).Name = InputBox("Enter Name") Personnel(i).YearOfBirth = InputBox("Enter the year of birth") Next Count the average age: Dim ThisYear, SumOfAge As Integer Dim AverageOfAge As Single ThisYear = DateTime.Now.Year For i = 0 To 4 SumOfAge = SumOfAge + (ThisYear - Personnel(i).YearOfBirth) Next AverageOfAge = SumOfAge / 5

52 11.2. Objects containing other objects Objects can contain other objects as their properties. In the following example, the class Person consists of three properties: Name, YearOfBirth and MyCar. MyCar again is an object type consisting of properties Model, LicensePlate and Speed. The MyCar can exist only in the context of a person object. Name YearOfBirth MyCar Model LicensePlate Speed In program code: Public Class Person Public Name As String Public YearOfBirth As Integer Public MyCar As Car End Class Public Class Car Public Model As String Public LicensePlate As Integer Public Speed As Integer End Class For instance: Create a person object: Dim p As New Person() p Set property values: p.name = "Lisa" p.yearofbirth = 1957 p Name YearOfBirth MyCar Name Lisa YearOfBirth 1957 MyCar

53 Before you can refer to MyCar object you have to create it: p.mycar = New Car() p Name Lisa YearOfBirth 1957 MyCar Model LicensePlate Speed Referring to hierarchical objects: Use the full path name with all the properties within the path: p.mycar.model = "Opel Vectra" p Name Lisa YearOfBirth 1957 MyCar Model LicensePlate Speed Opel Vectra If you want to create the MyCar object each time the Person object is created use New keyword in the class definition: Public Class Person Public Name As String Public YearOfBirth As Integer Public MyCar As New Car() End Class

54 12. Methods A method is a procedure that is specially designed for manipulating the object property values. The methods are part of the object itself. The method Rejuvenate () (suom. nuorennu) increments the property value YearOfBirth by 1. Object a: Name Jack Russell YearOfBirth 1981 Public Sub Rejuvenate() YearOfBirth = YearOfBirth + 1 To call the method write the method name with the object name separated by a dot. a.rejuvenate() Object a: Name Jack Russell YearOfBirth Public Sub Rejuvenate () YearOfBirth = YearOfBirth + 1 b.rejuvenate () Object b: Name Jane McCarthy YearOfBirth Public Sub Rejuvenate () YearOfBirth = YearOfBirth + 1

55 The methods are similar to sub programs and functions, but they differ essentially by their purpose. Methods are designed to process the data related to the objects of that class. Methods are part of the object class structure. Public Class Person Public Name As String Public YearOfBirth As Integer Public MyCar As New Car() Public Sub Rejuvenate() YearOfBirth = YearOfBirth + 1 End Class In this example rejuvenating is related only to Person objects. When calling the method, you always need a reference to the object that is used as the target of the operations of that method Methods as Sub programs The following example shows how the object class methods are like Sub programs. You can also use parameters with them. Example: Public Sub Rejuvenate (ByVal years As Integer) YearOfBirth = YearOfBirth + years 'Use the parameter value when calling the method: a.rejuvenate(3) Methods as Functions The following example shows how the methods can be written as functions. The function returns a numeric value between 0 and 3 indication the age group. Example: Public Function AgeGroup() As Integer Dim iage, iagegroup As Integer iage = Now.Year() - YearOfBirth If iage < 15 Then iagegroup = 0 ElseIf iage < 18 Then iagegroup = 1 ElseIf iage < 65 Then iagegroup = 2 Else iagegroup = 3 End If Return iagegroup End Function

56 Using the object class function: If a.agegroup() < 2 Then MessageBox.Show("Sorry, you are under aged") End If Constructors: Method New The method New is a special method that runs whenever an object is instantiated. Every object class has its New method by default, but you can write your own New method to complement the systems New method. Your own new method can be used, for example, when you want to set up default values for the object just created. Example: The following example shows how you can give the name for new Person objects as a parameter value and set 0 to Age property as a default value. Public Sub New(ByVal newname As String) DateOfBirth = 0 Name = newname Dim a As Person a = New Person("Jane") Name Jane DateOfBirth 0 Public Sub New(ByVal newname As String) DateOfBirth = 0 Name = newname Some useful methods A method is a procedure that is associated to a particular object or class. In program code, the notation for using a method is Object.Method(Value) or Class.Method(Value). For example the statement TextBox1.AppendText( Some more text ) uses the AppendText method of the TextBox1 object and the statement Convert.ToDouble(20) uses the ToDouble method of the Convert class Methods of String class The String class implements a collection of methods for string manipulation, including methods for formatting, concatenation, insert and replacement. String.Format(format as String, value as Object) Replaces each format specification in a specified string with the textual equivalent of a corresponding object's value. String.Format("The fragment is {0:##0.00}", 23.5) 23,50 String.Format("The percent is {0:0%}", 0.6) 60% String.Format("Now is {0:dd.MM.yy}", DateTime.Now())

57 String.Concat(s1 as String, s2 as String) Concatenates one or more instances of string. String.Concat("To be or", " not to be.") To be or not to be. StringObject.Insert(startIndex as Integer, s as String) Inserts a specified instance of string at a specified index position in this instance. Dim strobj As String = "To be to be." strobj.insert(6, "or not ") To be or not to be. StringObject.Replace(s1 as string, s2 as string) Replaces all occurrences of a specified string in this instance, with another specified string. Dim strobj As String = "To be or not to be." strobj.replace(" ", "-") To-be-or-not-to-be Methods of Convert class The convert class contains methods for converting data to the standard Visual Basic data types. Convert.ToDouble( ) Converts a value to Double. Convert.ToDouble(12) 12 Convert.ToString( ) Converts a value to String. Convert.ToString(12) 12 Convert.ToDateTime( ) Converts a value to DateTime. Convert.ToDateTime(" ")

58 Methods of Random class Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness. RandomObject.Next( ) Returns a random number as integer. Dim rndobj As New Random() Dim i As Integer = rndobj.next(1, 10) Returns a number greater than or equal to 1 and less than 10. RandomObject.NextDouble() Returns a random number as double between 0,0 and 1,0. Dim rndobj As New Random() Dim d As Double = rndobj.nextdouble() Returns a number greater than or equal to 0,0 and less than 1,0.

59 13. Property procedures The fields defined as Public work as the properties of the object. You can also define properties that do not necessarily have a specific equivalent field to store the property value in the object structure. But they create the property value dynamically when the property is called. (A naming convention: use _ when the property (or method) is meant to be used only from inside the class) Example 1: The Person class does not have a property Age, but it can be calculated on grounds of the YearOfBirth property when called. anage = a.age 22 Get Return _name Jack Russell _yearofbirth 1981 Public Property Age() To Get the property value: create and return the property value programmatically End Property In the same way, when the program sets the Age property, the object class property does some code that corresponds the behaviour to set the property value. In this case the _yearofbirth must be set to the value that corresponds the age. a.age = 23 Set _name Jack Russell _yearofbirth 1981 Public Property Age() To Set a new property value: do some code that corresponds to setting the property value End Property Properties are defined with property declarations within a class. They include a Get accessor and/or a Set accessor. The property procedure for the above example would look as follows: Public Property Age() Get Dim theage As Integer theage = Now.Year - _yearofbirth Return theage End Get Set(ByVal Value) _yearofbirth = Now.Year - Value End Set End Property anage = a.age a.age = 23

60 Example 2: Consider property FirstName, which is part of the Name property. Public Property FirstName() Get 'get characters up to the first space Dim index As Integer Dim strfirstname As String index = _name.indexof(" ") If index <= 0 Then strfirstname = "" Else strfirstname = _name.substring(0, index) End If Return strfirstname End Get Set(ByVal Value) 'replace the first name part with the value 'set by the caller Dim index As Integer Dim strfirstname As String index = _name.indexof(" ") If index <= 0 Then _name.insert(0, Value & " ") Else strfirstname = _name.substring(0, index) _name = _name.replace(strfirstname, Value) End If End Set End Property The intention of properties A property may be intended for only getting or setting a value of a field property. In VB.NET the modifiers ReadOnly and WriteOnly are used for excluding the other operation to be possible to exist. Example: If the property specifies the WriteOnly modifier, the property must have a setter and may not have a getter: Public WriteOnly Property Name() Set(ByVal Value) _name = Value End Set End Property

61 Equally, if the property specifies the ReadOnly modifier, the property must have a getter and may not have a setter. Public ReadOnly Property Name() Get Return _name End Get End Property If the property specifies no property type modifier, the property must have both a getter and a setter. Public Property Name() Get Return _name End Get Set(ByVal Value) _name = Value End Set End Property Encapsulation Encapsulation means, that one using properties or methods of an object doesn t have to know (or understand) how the functionality is physically performed. The user only needs to know what the object can do, he/she doesn t have to know, how the object does it Visibility The property values are Public when they can be referred to without any limitation. It means, that their values can be read and changed from all over the code. The same principle applies to methods as well: The methods are Public when the methods outside the class can call them. The properties and methods are Private when they can be referred only from inside the class where it has been declared. For instance: Public Class Person Public Name As String Private _yearofbirth As Integer Public Sub Rejuvenate() _yearofbirth = _yearofbirth + 1 End Class a.name = "Jack" OK a._yearofbirth = a._yearofbirth + 1 a.rejuvenate() OK Public Name As String Private _yearofbirth As Integer OK Public Sub Rejuvenate() _yearofbirth = _yearofbirth + 1

62 Use of the private properties The properties, which are public, can be set to pretty much anything; as long as they are of right data type. In the above example the variable Name can be set to any string value even though there might be only a certain set of valid names which are acceptable. Most often some control of setting the values is needed. That can be done by holding the actual values in private variables and let the user manipulate those values only through public property procedures. Public Class Car Private Colors() As String = {"Red", "Green", "Blue", "Black", _ "Yellow", "White"} Private _color As String Private _speed As Double Public Property Speed() Get Return _speed End Get Set(ByVal Value) If Value >= 0 And Value <= 200 Then _speed = Value End If End Set End Property Public Property Color() Get Return _color End Get Set(ByVal Value) Dim x As String For Each x In Colors If x = Value Then _color = Value Exit For End If Next End Set End Property End Class Dim acar As New Car() acar.color = "Red" acar.speed = 80

63 14. Advanced features of Objects Some advanced features of objects are inheritance and overriding. Inheritance builds up a hierarchy between classes: some classes inherit some others features. Inheriting classes are called subclasses or derived classes; the class from which a subclass inherits is called base class. Subclasses extend the inherited features with features of their own. They can also replace an inherited feature. That is called overriding. So, in addition to inheriting all the public features, that a base class has, a subclass can add more features to it and replace (override) some of the features inherited Inheritance Inheritance is used to create classes that have everything that another class has and something more. Consider the following case in which we have classes Person and Student: Public Class Person Private _name As String Private _yearofbirth As Integer Public Sub Rejuvenate () _yearofbirth = _yearofbirth + 1 End Class The Class Student has all the same properties as Person, but the Student also has properties of its own. In other words: The Student Class inherits the class Person. In this case class Person is the base class and class Student is the subclass. Public Class Student Private _name As String Private _yearofbirth As Integer Public Sub Rejuvenate() _yearofbirth = _yearofbirth + 1 Public Credits As Integer Public Sub AddCredits(ByVal C As Integer) Credits = Credits + C End Class Copied from Person Class Own properties and Methods The object class description can be written using keyword Inherits as follows: Public Class Student Inherits Person Public Credits As Integer Public Sub AddCredits(ByVal C As Integer) Credits = Credits + C End Class

64 Special case: constructor The constructors are not inheritable. If you have written a constructor (method New) in the base class, you have to write a constructor in the subclass as well. In the first row of the constructor in the subclass needs to be a call for the base class s constructor. The keyword MyBase refers to the base class s members. The keyword needs to be used when calling a method in the base class, which has the same name as a method in the subclass. The base class s methods with different name than any in the subclass can be called without the MyBase keyword. The base class Public Sub New(ByVal newname As String) _name = newname The subclass Public Sub New(ByVal newname As String) 'Call the base class s (Person) New method first MyBase.New(newName) 'The code for subclass s New method Credits = Inheriting the Object-class The Object-class is the mother of all classes. Even though the Inherits keyword is not used when writing a class, the class will automatically inherit the class Object. The two useful methods, which are in use of all classes through the Object-class are ToString() and GetType(). ToString() returns a string presentation of the object. If it will not be overridden, it will return the name of the class. GetType() returns a data type of the object.

65 14.2. Overriding In some cases it is desirable to override methods, which are implemented in the base class. In order to override a method, it has to be marked with keyword Overridable in the base class. The overriding happens in the subclass by adding the keyword Overrides to the front of the method. The base class Public Class Person Private Name As String Private _yearofbirth As Integer Public Overridable Sub Rejuvenate() _yearofbirth += 1 'This function converts the object to string Public Overrides Function ToString() As String Return _name End Function End Class The subclass Public Class Student Inherits Person Public Credits As Integer Public Sub AddCredits(ByVal C As Integer) Credits += C 'Rewrite the Rejuvenate method for student objects Public Overrides Sub Rejuvenate() If _yearofbirth < System.DateTime.Now.Year - 18 Then _yearofbirth += 1 End If End Class

66 14.3. Overloading Overloading a procedure means defining it in multiple versions, using the same name but different argument lists. The purpose of overloading is to define several closely related versions of a procedure without having to differentiate them by name. The different type of the return value is not enough to distinguish procedures from each other, the argument list needs to be different. Overloading is especially useful when offering same functionality for different data types. Public Overloads Function Add(ByVal Number1 As Integer, _ ByVal Number2 As Integer) As Integer Return Number1 + Number2 End Function Public Overloads Function Add(ByVal Number1 As String, _ ByVal Number2 As String) As Integer Return Convert.ToInt32(Number1) + Convert.ToInt32(Number1) End Function Public Overloads Function Add(ByVal Number1 As Double, _ ByVal Number2 As Double) As Double Return Number1 + Number2 End Function The keyword Overloads indicates that a function is overloaded. Without overloading, one would need to create distinct names for each procedure, even though they do the same thing, as shown next: Public Function AddIntegers(ByVal Number1 As Integer, _ ByVal Number2 As Integer) As Integer Return Number1 + Number2 End Function Public Function AddStrings(ByVal Number1 As String, _ ByVal Number2 As String) As Integer Return Convert.ToInt32(Number1) + Convert.ToInt32(Number1) End Function Public Function Add(ByVal Number1 As Double, _ ByVal Number2 As Double) As Double Return Number1 + Number2 End Function The overloaded Add function shown above can be called with any of the following lines of code: Add(2, 3) Add("2", "3") Add(2.0, 3.0)

67 14.4. Keyword Overloads The use of the keyword Overloads is obligatory only with the methods: 1. in the subclass, which are overloading methods in the base class; 2. in any class, if there is written at least one overloading method using the Overloads keyword. Public Class Adder Public Function Add(ByVal Number1 As Integer, _ ByVal Number2 As Integer) As Integer Return Number1 + Number2 End Function Public Function Add(ByVal Number1 As String, _ ByVal Number2 As String) As Integer Return Convert.ToInt32(Number1) + Convert.ToInt32(Number1) End Function End Class Public Class DoubleAdder Inherits Adder Public Overloads Function Add(ByVal Number1 As Double, _ ByVal Number2 As Double) As Double Return Number1 + Number2 End Function End Class The keyword Overloads is not used with constructors.

68 14.5. Example Using both overriding and overloading. 'base class Person Public Class Person Public Name As String Public yearofbirth As Single 'use this function when no parameter is passed Public Overloads Function AgeGroup() As Integer If Now.Year - yearofbirth < 18 Then Return 1 Else Return 2 End If End Function 'use this function when one integer parameter is passed Public Overloads Function AgeGroup(ByVal noofgroups As Integer) As Integer Dim scale As Integer scale = 100 / noofgroups Return Int((Now.Year - yearofbirth) / scale) + 1 End Function 'use this function in case of Person objects Public Overridable Function RightToLoan() As Boolean If Now.Year - yearofbirth >= 18 Then Return True Else Return False End If End Function End Class 'sub class Student Public Class Student Inherits Person 'use this function in case of Student objects (and not the inherited one) Public Overrides Function RightToLoan() As Boolean Return False End Function End Class

69 15. Arrays and Collections When writing software there is often need to store a set of related values together with the same variable name. For these purposes VB.NET provides the array data type and the collection object. Arrays are lists of data that have a single data type. Collections are groups of objects Array data type The array data type in Visual Basic.NET is zero-based. It means that the lower bound for an array is always 0. The variables contained in an array, must all be of the same type, and this type is called the element type of the array. Each element of an array is initialized to the default value of its type. Dim Numbers(4) As Integer Numbers In the declaration: Dim ArrayName(n) As ElementType the number n is the upper bound of the array. Thus, the array elements are ArrayName(0) through ArrayName(n), and the array has n+1 elements, that is, it s length is n+1. Arrays can be initialized with declaration. Dim Numbers() As Integer = {10, 20, 30, 40, 50} Numbers Multidimensional arrays are declared similarly: Example 1: Dim LotNumbers(3,1) As Integer LotNumbers

70 Example 2: Dim MoreNumbers(,) As Integer = {{1, 10}, {2, 20}, {3, 30}, {4, 40}, _ {5, 50}} MoreNumbers The value of MoreNumbers(0,0) is 1 and the value of MoreNumbers(4,1) is ReDim statement The ReDim statement is used to allocate and reallocate storage space for an array variable. It means that the size of one or more dimensions of an array that has already been declared can be changed. Dim Numbers() As Integer 'Declaration of an array variable ReDim Numbers(4) 'Allocate 5 elements For i = 0 To Numbers.GetUpperBound(0) 'Gets the upper bound of the 'given dimension Numbers(i) = i 'Initialize array Next i ReDim releases the existing array and creates a new array with the same number of dimensions it originally had (= ReDim cannot change the number of dimensions of an array!). The elements of the new array are initialized to the default value of their data type unless otherwise declared (keyword Preserve, see below). ReDim Numbers(9) 'Resize to 10 elements For i = 0 To Numbers.GetUpperBound(0) Numbers(i) = i * 2 'Initialize array Next i If the Preserve keyword is included, Visual Basic copies the elements from the existing array to the new array. ReDim Preserve Numbers(14) 'Resize to 15 elements and save the contents of the elements

71 It is possible to resize only the last dimension of the array by using the Preserve keyword (= ReDim can only change the rightmost dimension). Every other dimension needs to be specified the same size it already has in the existing array. Private Nums(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} 'The size of the array is now (1,4) Nums ReDim Preserve Nums(1, 6) Nums ReDim Preserve Nums(2, 6) Error ReDim Nums(2, 2) Nums

72 15.3. System.Array Class All arrays are internally implemented as objects of the class System.Array. The class contains useful methods for dealing with arrays. Below are explained some of the members of the class Properties objarray.length Gets the total number of elements in all the dimensions of the Array object. Dim intd2array(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} intd2array.length 10 objarray.rank Gets the rank (number of dimensions) of the Array object. Dim intd2array(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} intd2array.rank Shared Methods Array.IndexOf(objArray As Array, Value As ElementType) Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array. Dim strarray() As String = {"To", "be", "or", "not", "to", "be"} Array.IndexOf(strArray, "be") 1 Array.LastIndexOf(objArray As Array, Value As ElementType) Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array. Dim strarray() As String = {"To", "be", "or", "not", "to", "be"} Array.LastIndexOf(strArray, "be") 5

73 Array.Reverse(objArray As Array) Reverses the order of the all or a part of the elements in a one-dimensional. Dim strarray() As String = {"To", "be", "or", "not", "to", "be"} Array.Reverse(strArray) strarray: {"be", "to", "not", "or", "be", "To"}... Dim intarray() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0} Array.Reverse(intArray, 2, 5) 'The second parameter defines the 'starting index of the section to be 'reversed, the third one the number of 'elements to be reversed intarray: {1, 2, 7, 6, 5, 4, 3, 8, 9, 0} Array.Sort(objArray As Array) Sorts the elements in one-dimensional Array objects. Dim intarray() As Integer = {15, 30, 20, 5, 10, 25} Array.Sort(intArray) intarray: {5, 10, 15, 20, 25, 30} Instance Methods objarray.setvalue(value As ElementType, Index1 As Integer, Index2 As Integer) Sets the specified element in the current Array to the specified value. Dim intd2array(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} intd2array.setvalue(100, 1, 0) intd2array: {{10, 20, 30, 40, 50}, {100, 2, 3, 4, 5}} objarray.getvalue(index1 As Integer, Index2 As Integer) Gets the value of the specified element in the current Array. Dim intd2array(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} intd2array.getvalue(0, 4) 50

74 objarray.getlength() Gets the number of elements in the specified dimension of the Array. Dim intd2array(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} intd2array.getlength(0) 2 intd2array.getlength(1) 5 objarray.getupperbound() Gets the upper bound of the specified dimension in the Array. Dim intd2array(,) As Integer = {{10, 20, 30, 40, 50}, {1, 2, 3, 4, 5}} intd2array.getupperbound(0) 1 intd2array.getupperbound(1) 4

75 15.4. Collections A collection object is a container for objects of all types; it can hold standard data types as well as objects. Collections can be created as any other objects by using the constructor. Dim Persons As New Collection() A collection is an indexed set of objects that contains some functionality for handling the data stored in it. It is like an array but its elements are all references to objects and the base is 1 by default. So, the index in a collection is an integer between one and the number of items in the collection. Count Name Name Type Name Name YearOfBirth Colour YearOfBirth YearOfBirth Members of the Collection Class A collection object includes properties and methods, which can be used for inserting, deleting, and retrieving the items in the collection. Property Count Item(index) Method Add(item) Remove(index) Description Returns the number of objects in a collection. Returns a specific member of a Collection object either by position or by key. Description Adds a member to a Collection object. Removes a member from a Collection object by index or by key. Example 1: In the example below a collection named Information is created and three elements of different data types are added to it. Dim Information As New Collection() Information.Add("Jack Russell") Information.Add(12) Dim p As New Person("Mona") Information.Add(p) 'OR: 'Information.Add(New Person("Mona")) Information.Count 'returns 3 Information.Remove(1) 'removes the item by index 1 Information.Count 'returns 2

76 Example 2: The next example adds and initializes three Person objects to the collection Persons and then displays the property values of the items in the collection. Dim Persons As New Collection() Dim i As Integer Persons.Add(New Person("Karl")) Persons.Add(New Person("Valerie")) Persons.Add(New Person("Lisa")) Persons.Item(1).YearOfBirth = 1981 Persons.Item(2).YearOfBirth = 1982 Persons.Item(3).YearOfBirth = 1983 For i = 1 To Persons.Count MessageBox.Show(Persons.Item(i).Name & " " & Persons(i).Age) Next Note that the first call explicitly specifies the Item property, but the second does not. Both calls work. (Objects may be defined default properties which are used if no property is explicitly called. Item is defined to be the default property of Collection object.) Keys of Collection Objects Collection objects update their numeric index numbers automatically when elements are added to it and deleted from it; so the numeric index of a certain element may change often. Therefore referring to a certain element is not possible with index values. For that Visual Basic offers the Keys. A key is a unique string expression that can be attached to the items inserted to a collection. It can be used instead of a numric index to access a member of the collection. A key is attached to the item when adding it to the collection: objcollection.add(item, "Key") Dim Persons As New Collection() Persons.Add(New Person("Karl"), "K") Persons.Add(New Person("Valerie"), "V") Persons.Add(New Person("Lisa"), "L") 'The following statement displays Karl MessageBox.Show(Persons("K").Name) Persons.Remove("V") 'removes the item by key "V"

77 15.5. For Each...Next loop For Each Next loop cycles through elements in a collection or in an array one at a time. The body of the loop is used to process the individual elements of the group. For Each <element> In <group> body Next Where <element> is a variable that is used to iterate through the elements of the group. <group> is the name of the variable of a collection or an array that is to be processed. 'The For loop above in Example 2: 'For i = 1 To Persons.Count ' MessageBox.Show(Persons.Item(i).Name & " " & Persons(i).Age) 'Next ' can be written as follows: Dim obj As Person For Each obj In Persons MessageBox.Show(obj.Name & " " & obj.age) Next

78 Control Structures Conditional statements If Then Else If condition [ Then ] [ statements ] [ ElseIf elseifcondition [ Then ] [ elseifstatements ] ] [ Else [ elsestatements ] ] End If -or- If condition Then [ statements ] [ Else [ elsestatements ] ] Dim number, digits As Integer number = Convert.ToDouble(InputBox("Enter a number")) If number < 10 Then digits = 1 ElseIf number < 100 Then digits = 2 Else digits = 3 End If Select Case Select [ Case ] testexpression [ Case expressionlist [ statements ] ] [ Case Else [ elsestatements ] ] End Select Dim number As Integer = 8 Select Case number Case 1 To 5 Debug.WriteLine("Between 1 and 5, inclusive") Case 6, 7, 8 Debug.WriteLine("Between 6 and 8, inclusive") Case 9 To 10 Debug.WriteLine("Equal to 9 or 10") Case Else Debug.WriteLine("Not between 1 and 10, inclusive") End Select

79 Loop Structures While End While While condition [ statements ] [ Exit While ] [ statements ] End While Dim counter As Integer = 0 While counter < 20 counter += 1 ' Insert code to use current value of counter. End While MessageBox.Show("While loop ran " & counter & " times.") Do Loop Do { While Until } condition [ statements ] [ Exit Do ] [ statements ] Loop -or- Do [ statements ] [ Exit Do ] [ statements ] Loop { While Until } condition Sub exitdoexample() Dim counter As Integer = 0 Dim number As Integer = 8 Do Until number = 10 If number <= 0 Then Exit Do number -= 1 counter += 1 Loop MessageBox.Show("The loop ran " & counter & " times.")

80 For Next For counter [ As datatype ] = start To end [ Step step ] [ statements ] [ Exit For ] [ statements ] Next [ counter ] Dim d As Double Dim l As Long For l = 1 To 20 Step 1 d = d + l Next MessageBox.Show("The sum of numbers is " & d) For Each Next For Each element [ As datatype ] In group [ statements ] [ Exit For ] [ statements ] Next [ element ] Dim found As Boolean = False Dim thiscollection As New Collection For Each thisobject In thiscollection If thisobject.tostring = "Hello" Then found = True Exit For End If Next

81 16. Objects in a ListBox and Shared members How to use objects in a ListBox ListBoxes are discussed more in detail in chapter 6 One more important control. In this chapter is discussed how objects are used in ListBoxes. When using objects in a ListBox, the programmer needs to decide, what to be displayed of the object: a value of a certain field or property, or maybe a combination of them, or maybe something else... If no action is made, the name of the object class is shown in the ListBox. That s because the value to be displayed is the value of the ToString method of the object, which is inherited from the Object class. So, in order to display something else, the ToString method needs to be overridden in the subclass. We want to attach a Person object for each item in a ListBox. A person consists of fields Name and HourlyPay, but we want only the value of the field Name to represent the object in ListBox. Public Overrides Function ToString() As String Return Name End Function ListBox lbxpersons In this example, the ListBox contains references to objects of class Person. lbxpersons Jack Jane Ken Mary Name Jack HourlyPay 22 Name Jane HourlyPay 11 Name Ken HourlyPay 55 Name Mary HourlyPay 33

82 Public Class Person Public Name As String Public HourlyPay As Decimal 'When adding this object into a ListBox, the system 'shows the object as a string value using the objects ToString method. 'In the case of the Person object, we want the method to return the value 'of the field Name. It means that the method ToString, which is inherited 'from the Object class, needs to be overridden: Public Overrides Function ToString() As String Return Name End Function End Class Public Class FormPersonnel Inherits System.Windows.Forms.Form Private Sub btnaddperson_click( ) Handles btnaddperson.click AddPerson(txtName.Text, txtpay.text) Private Sub btnlistpays_click( ) Handles btnlistpays.click 'List all the hourly pays into a label Dim obj As Person lblpays.text = "" For Each obj In lbxpersons.items lblpays.text = lblpays.text & obj.hourlypay & ControlChars.NewLine Next Private Sub lbxpersons_selectedindexchanged( ) _ Handles lbxpersons.selectedindexchanged 'shows the hourly pay of the selected person in a MessageBox MessageBox.Show(lbxPersons.Items(lbxPersons.SelectedIndex).HourlyPay) Private Sub AddPerson(ByVal Name As String, ByVal HourlyPay As String) If Name <> "" And HourlyPay <> "" Then If IsNumeric(HourlyPay) Then 'create a new person and initialize it Dim NewPerson As New Person() NewPerson.Name = Name NewPerson.HourlyPay = Convert.ToDecimal(HourlyPay) 'add the Person object into the list lbxpersons.items.add(newperson) End If End If End Class

83 16.2. Shared members Shared members are properties, procedures, and fields that are shared by all instances of a class. To put it another way, shared members belong to the class as a whole, rather than to its individual instances. They can be accessed without creating an instance of the class. Shared members are defined using the Shared keyword and they are accessed by qualifying them either with the class name. The System.Array class has the shared method Sort. It is declared Public Shared Sub Sort(array As Array) and used: Dim array As Array Array.Sort(array) Shared fields and properties Shared fields and properties are useful when there s a need for keeping track of data that is independent of any particular instance of the class; for instance for keeping track on number of certain objects in existence at any given time. Thinking this way, shared fields and properties behave like global variables that can be accessed with qualification of the class name. Without shared fields and properties, one would need to use module-level variables to achieve the same effect. However, module-level variables can make classes difficult to understand and maintain. Furthermore, using module-level variables in this way violates the concept of encapsulation that classes represent Shared procedures Shared procedures and properties do not have access to instances of a class; they may only access shared members. In this example the variable x is an instance member because it s not declared as Shared. However, the procedure setxandy is shared among all instances of class sample. Therefore it has no connection with particular instances, and it cannot access any instance variables. It can access only shared members. Error Class sample Public x As Integer Shared y As Integer Public Shared Sub setxandy() x = 10 y = 10 End Class

84 Example Public Class Form1 Public Class Item Public Shared Count As Integer = 1 Public SerialNumber As Integer Public Name As String Public Sub New(ByVal Name As String) 'Use Count to initialize SerialNumber. Me.SerialNumber = Count Me.Name = Name 'Increment the shared variable Count += 1 Public Sub InstanceMethod() MessageBox.Show("Information: " & Me.SerialNumber & _ ControlChars.Tab & Me.Name) Public Shared Sub SharedMethod() MessageBox.Show("Current value of Count: " & Count) End Class 'Class Item Private Sub testshared_click(byval sender As System.Object, _ ByVal e As System.EventArgs) Handles testshared.click 'Create two instances of the class. Dim item1 As New Item("table") Dim item2 As New Item("chair") item1.instancemethod() item2.instancemethod() Item.SharedMethod() End Class 'Class Form1

85 17. Programming with multiple forms Forms in VisualBasic.NET are objects; they are instances of the System.Windows.Forms.Form Class. Besides of having functionality, the class provides a visual interface. A class can become a form by inheriting the systems Form class. It also can become a form hierarchically by inheriting another class, which inherits the systems Form class. In this case all the controls placed on the form are also inherited including the functionality behind them. Example 1: In the following example, the main form contains two other forms. (Note that these forms are objects inside another form.) Click Click Public Class MainForm Inherits System.Windows.Forms.Form Private Form2 As New SecondForm() Private Form3 As New ThirdForm() Private Sub btnshowsecond_click( ) Handles btnshowsecond.click Form2.Show() Private Sub btnshowthird_click( ) Handles btnshowthird.click Form3.Show() End Class Public Class SecondForm Inherits System.Windows.Forms.Form Private Sub btnhideme_click( ) Handles btnhideme.click Me.Hide() End Class

86 Public Class ThirdForm Inherits SecondForm Private Sub ThirdForm_Load( ) Handles MyBase.Load Me.Text = "Third Form" End Class

87 Example 2: In the following example, the form objects are outside the scope of the form (Module1). This enables to communicate and switch between forms. f: txtcount Text... f1: txtcount Text... Module Module1 Public f1 As New frmsecondform() Public f As frmmain End Module Public Class frmmain Private Sub frmmain_load( ) f = Me Private Sub btnshow_click( ) f1.show() End Class Public Class frmsecondform Private Sub btnback_click( ) Me.Hide() Private Sub btnaddthis_click( ) txtcount.text = Convert.ToInt16(txtCount.Text) + 1 Private Sub btnaddmain_click( ) f.txtcount.text = Convert.ToInt16(f.txtCount.Text) + 1

88 17.1. Forms containing other forms A form being able to contain other forms is called a Multiple Document Interface (MDI) form. An MDI application consists of a parent MDI form and multiple child forms, which are kept contained within the parent. A parent form is created from a regular form by setting its IsMdiContainer property to True. To open a regular form as a child form within a parent form, the MdiParent property needs to be set to the parent form. Example: 1. Create a Windows application and set the IsMdiContainer property of the form to True: 2. Add a new form to the project (Project Add Windows Form...), which shall be the class for instances of the child forms. 3. Create instances of the child form in the parent form and set their MdiParent properties to it. Public Class ParentForm Inherits System.Windows.Forms.Form Private ChildForm1 As New ChildForm() Private ChildForm2 As New ChildForm() Private Sub ParentForm_Load( ) Handles MyBase.Load ChildForm1.MdiParent = Me ChildForm1.Show() ChildForm2.MdiParent = Me ChildForm2.Show() End Class

89 4. The MenuStrip control contains functionality for listing the available child forms that are owned by the parent. This functionality is turned on by giving the desired menu item, where the list of the child windows shall be shown, as value for the property MdiWindosListItem, 5. The application looks like follows:

90 18. Working with files In the sections below are examples for reading and writing text to and from a file and for using dialog boxes for opening and saving files. In order to get the file handling classes to operate, they need to be included to the program by importing the desired system s namespace. That is done by adding the statement for importing the namespace System.IO to the program s first row. Imports System.IO Reading text from a file.net has a class StreamReader, which is designed for reading text from a file. In order to read text from a file, an instance of the StreamReader class is created by using the File class s shared OpenText method. The name of the file to be read from is given for this method as a parameter and the method then returns a StreamReader object pointing to the desired file as its return value. Dim inputstream As StreamReader inputstream = File.OpenText("c:\ReadMe.txt") The actual reading happens by using any of the StreamReader object s methods Read, ReadLine or ReadToEnd. Example 1: In this example, the contents of the file c:\readme.txt are read into a textbox named txtreadthis when the form is loaded. Private Sub Form_Load( ) Handles MyBase.Load Dim inputstream As StreamReader inputstream = File.OpenText("c:\ReadMe.txt") txtreadthis.text = inputstream.readtoend() inputstream.close() The Close method closes the file. txtreadthis.select(0, 0) The Select method removes the selection in the text box.

91 Example 2: The following program prints all the other customer information in the file c:\customers.dat onto the text box named txtcustomerinfo, except for the information of the customer who s last name is Bacon. Private Sub btnshowcustomers_click( ) Handles btnshowcustomers.click Dim inputstream As StreamReader Dim strline As String inputstream = File.OpenText("c:\Customers.dat") strline = inputstream.readline() While Not strline Is Nothing The ReadLine method returns value Nothing when the end of the input stream is reached. If Not strline.startswith("bacon") Then txtcustomerinfo.appendtext(strline & ControlChars.NewLine) End If strline = inputstream.readline() End While inputstream.close() Writing text to a file.net has a class StreamWriter, which is designed for writing text to a file. In order to write text to a file, an instance of the StreamWriter class needs to be created. That is done by calling the shared CreateText method of the File class. The name of the file to be written to is given for this method as a parameter and the method then returns a StreamWriter object pointing to the desired file as its return value. Dim outputstream As StreamWriter outputstream = File.CreateText("c:\WriteMe.txt") The CreateText method will create the file, if it doesn t exist. If the file does exist, its contents are overwritten. The actual writing happens by using the StreamWriter object s methods Write or WriteLine.

92 Example 3: In this example a copy of the file c:\customers.dat is created to the file c:\copyofcustomers.dat. Then a new line of customer information is added into the copy file. The information is given in text boxes. Finally the original file c:\customers.dat is deleted and the copy file is renamed to be the c:\customers.dat file. 1. In the beginning, the file c:\customers.dat looks like as follows: 2. When the end-user clicks the Add Customer button, the following code is to be executed: Private Sub btnaddcustomer_click( ) Handles btnaddcustomer.click Dim outputstream As StreamWriter 'Coping an existing file to a new file: 'File.Copy(SourceFile As String, DestinationFile As String, _ OverWrite As Boolean) 'When setting the OverWrite parameter to True, the destination file 'can be overwritten, else if the OverWrite parameter is set to False, 'overwriting a file of the same name is not allowed. File.Copy("c:\Customers.dat", "c:\copyofcustomers.dat", True) 'Opening a file for appending text to it: 'If the file specified as a parameter does not exist, it is created. 'If the file does exist, write operations to the StreamWriter append 'text to the file. outputstream = File.AppendText("c:\CopyOfCustomers.dat") outputstream.writeline("{0}, {1}", txtname.text, txtstate.text) outputstream.close() File.Delete("c:\Customers.dat") File.Move("c:\CopyOfCustomers.dat", "c:\customers.dat") 3. Finally, the file c:\customers.dat looks like as follows:

93 18.3. Open File Dialog The OpenFileDialog control represents a common dialog box that displays the control that allows the user to open a file. Example 4: Private Sub btnopenfile_click( ) Handles btnopenfile.click Dim strfilename As String 'Set title OpenFileDialog1.Title = "Please, enter the file name" 'Set the initial directory OpenFileDialog1.InitialDirectory = "c:\temp" 'Set the filter "Description Pattern Description Pattern" OpenFileDialog1.Filter = "Data files *.dat All files *.*" 'Invoke the Open File dialog box OpenFileDialog1.ShowDialog() Title Initial directory FileName Filter 'Now the file name is in the property value: OpenFileDialog1.FileName 'Get the file name entered by the user strfilename = OpenFileDialog1.FileName

94 Example 5: The following example continues the previous example by adding code for listing the file contents on a textbox named txtcustomerinfo. All the information of one customer is saved in the file on one row, separated by a comma. The customer information is shown in the textbox separated by a tabulator. Private Sub btnopenfile_click( ) Handles btnopenfile.click Dim inputstream As StreamReader Dim strline, strinfo, strcustomerinfo() As String Dim separator() As Char = {","c} Dim strfilename As String OpenFileDialog1.Title = "Please, enter the file name" OpenFileDialog1.InitialDirectory = "c:\temp" OpenFileDialog1.Filter = "Data files *.dat All files *.*" OpenFileDialog1.ShowDialog() strfilename = OpenFileDialog1.FileName txtcustomerinfo.clear() inputstream = File.OpenText(strFileName) strline = inputstream.readline() While Not strline Is Nothing strcustomerinfo = strline.split(separator) For Each strinfo In strcustomerinfo txtcustomerinfo.appendtext(strinfo & ControlChars.Tab) Next txtcustomerinfo.appendtext(controlchars.newline) strline = inputstream.readline() End While inputstream.close()

95 18.4. Save File Dialog The SaveFileDialog control represents a common dialog box that allows the user to specify options for saving a file. 'The types for allowing reading and writing on files are defined in the 'namespace System.IO. That namespace needs to be imported to the application 'in order for the code below to work. That is done by adding the imports 'statement to be the first row of the code. Imports System.IO Private Sub btnsavetofile_click( ) Handles btnsavetofile.click Dim strfilename As String Dim outputstream As StreamWriter SaveFileDialog1.Title = "Save account information" SaveFileDialog1.InitialDirectory = "c:\temp" SaveFileDialog1.Filter() = "Data files (*.dat) *.dat All files (*.*) *.*" If SaveFileDialog1.ShowDialog() = DialogResult.OK Then strfilename = SaveFileDialog1.FileName outputstream = File.AppendText(strFileName) outputstream.writeline(txtname.text & ", " & txtbalance.text) outputstream.close() End If

96 19. Retrieving data from a database There are four things to do in order to get some data out of a database: 1) connecting to a database, 2) executing commands (SQL for selecting the desired data), 3) retrieving results, and 4) closing the connection. For all these purposes there are special objects in.net: a Connection object, a Command object and a DataReader object. These objects work together as shown in the following picture. Database: C:\DBFile.mdb Connection ConnectionString Command CommandText Connection ExecuteReader() DataReader Read() Item( ) ID Name

97 19.1. Connecting to a database (Connection object) A Connection is an object that moves data between a data store and the application. It has a property ConnectionString that defines all the information needed for establishing a connection to a database. The string includes the database provider, user information, data source, etc. Dim MyConnection As New OleDbConnection() MyConnection.ConnectionString = "Provider= Microsoft.Jet.OLEDB.4.0; _ Data Source= C:\DataBases\CustomerOrders.mdb; _ UserID=Admin; Password= "";" The ConnectionString property can be set only when the connection is closed. Keyword value pairs must be separated by a semicolon (;). If a property name (keyword) occurs more than once in the connection string, the value associated with the last occurrence is used. For opening a connection to a database the Open method of the Connection object is used. It opens the connection with the property settings specified by the ConnectionString. A connection must always be closed using the Connection objects Close method. Dim MyConnection As New OleDbConnection() MyConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; _ Data Source=c:\DBFile.mdb;" MyConnection.Open() 'code for working with the connection MyConnection.Close() DB Connection Executing SQL select commands (Command object) A Command object executes a SQL command to a database using a Connection object. The Command object has a Connection property, which is set to a Connection object to be used. The SQL statement is hold in a property named CommandText. Example: Let s assume that the variable named MyConnection is defined as in the previous example. Dim MyCommand As New OleDbCommand() MyCommand.Connection = MyConnection MyCommand.CommandText = "SELECT ColumnName FROM TableName" DB Connection Command CommandText = "SELECT " Connection

98 19.3. Fetching data and working with it (DataReader object) A DataReader object is used to retrieve a read-only, forward-only stream of data rows from the database. It is also used for iterating through the fetched data Retrieving data from a database To create a DataReader object, the ExecuteReader method of the Command object shall be called. This method sends the value of the CommandText property to the Connection and builds a DataReader object. So, the constructor of the DataReader shall not be called directly. The DataReader must be closed when it is not needed any more. That ll happen by calling its Close method. For instance: Dim MyReader As OleDbDataReader MyReader = MyCommand.ExecuteReader() 'code for working with the fetched data MyReader.Close() DB Connection Command CommandText = "SELECT " Connection ExecuteReader() DataReader ID Name Iterating through the data Once the data has been fetched from the database, the DataReader can be used for iterating through the data with its Read method. A call to that method advances the DataReader to the next record. It means that the Item property of the DataReader points to the next record. Method Read is a function that returns false if there are no records left, otherwise it returns true. A value of a certain column of one record can be referred by passing the DataReaders Item property the column name or the column ordinal as a parameter. Example 1: Let s assume that the DataReader object named MyReader has been advanced to the second record. MyReader.Item("Name") MyReader.Item(0) DataReader ID Name

99 Example 2: In this example the DataReader object named MyReader already exists in the beginning. Then the data is iterated using the While loop and the value of the Name column of each record is shown for the user in a message box. Dim NotEof As Boolean 'The default position of the OleDbDataReader is prior to the first 'record. Therefore, you must call Read to begin accessing any data. NotEof = MyReader.Read() While NotEof MessageBox.Show("Value: " & MyReader.Item("Name")) NotEof = MyReader.Read() End While MyReader.Close() DB Connection Command CommandText = "SELECT " Connection ExecuteReader() DataReader Read() Item( ) ID Name

100 19.4. Example In the next example the Customer names are fetched from an Access database into a DataReader object and they are shown in a ComboBox. 'The objects for handling databases are defined in 'the namespace System.Data.OleDb 'That namespace needs to be imported to the application 'in order for the code below to work Imports System.Data.OleDb Dim MyCommand As New OleDbCommand() Dim MyReader As OleDbDataReader Dim MyConnectionString As String = _ "Provider=Microsoft.Jet.OLEDB.4.0; _ Data Source=c:\DataBases\CustomerOrders.mdb;" 'An OleDbConnection object can also be initialized with the 'overloaded version of its constructor, which is given 'the ConnectionString as a parameter: Dim MyConnection As New OleDbConnection(MyConnectionString) 'open a connection to the database MyConnection.Open() 'set MyCommands Connection property to point to MyConnection MyCommand.Connection = MyConnection 'write the SQL statement to be executed MyCommand.CommandText = "SELECT CustID, Name FROM Customer" 'build a DataReader MyReader = MyCommand.ExecuteReader() Dim NotEof As Boolean NotEof = MyReader.Read() While NotEof 'read the data row by row from the DataReader object 'into a Combo Box cbxcustomer cbxcustomer.items.add(myreader.item("name")) NotEof = MyReader.Read() End While 'always call Close when done with reading MyReader.Close() 'close the connection when done with it MyConnection.Close()

101 19.5. Selecting records There are two ways of selecting the records needed: 1) constructing a SQL statement for meeting the criteria, or 2) selecting the records in the program code. List the customers meeting a given criteria. Fetch the customers from a given Person ID MyCommand.CommandText = _ "SELECT CustID, Name FROM Customer" & _ " WHERE CustID >=" & txtid.text Fetch the customers by given initials MyCommand.CommandText = _ "SELECT CustID, Name FROM Customer" & _ " WHERE Name LIKE '" & txtinitials.text & "%'" Remember to add the single quotes into the string represented in an SQL statement. Select the records in your program code If myreader.item("custid") >= Convert.ToSingle(txtID.Text) Then txtoutput.appendtext(myreader.item("name") & ControlChars.NewLine) End If

102 20. More features of the Command Class Besides of the ExecuteReader method that returns a populated DataReader object, Command Class offers methods for executing commands, which do not return values and for retrieving only a singleton value. The Command Class also has a property for holding parameters of the SQL statement Processing Non Query Commands SQL statements that modify data (such as Insert, Update or Delete) are called Non Query Commands. They do not return any rows and therefore do not need a DataReader object. For queries of that type the Command object has the ExecuteNonQuery method. Instead of returning a populated DataReader object, it returns the number of rows, which the command has affected. Using the ExecuteNonQuery method happens the same way as using the ExecuteReader method. Database: C:\DBFile.mdb Connection ConnectionString Command CommandText= "INSERT " Connection ExecuteNonQuery() Example 1: Update the Balance field value. Dim n As Integer Dim MyCommand As New System.Data.OleDb.OleDbCommand() MyCommand.Connection = MyConnection MyCommand.CommandText = "UPDATE Customer SET Balance = 1.1*Balance" MyConnection.Open() n = MyCommand.ExecuteNonQuery() MyConnection.Close() MessageBox.Show(n & " rows were updated") Example 2: Insert a new Customer. Dim MyCommand As New System.Data.OleDb.OleDbCommand() MyCommand.Connection = MyConnection 'Construct the SQL command MyCommand.CommandText = _ "INSERT INTO Customer(CustID, Name, Area, Balance ) " & _ "VALUES ('" & txtcustid.text & "','" & txtname.text & _ "','" & txtarea.text & "'," & txtbalance.text &")" 'Execute the SQL command MyConnection.Open() MyCommand.ExecuteNonQuery() MyConnection.Close()

103 20.2. Retrieving a singleton value The Command object offers method ExecuteScalar for returning a singleton value from the data source.this requires less code than using first the ExecuteReader method and then performing the operations necessary to generate the single value using the data returned by a DataReader. Example: Get the count of the customers in the data source. MyCommand.CommandText = "SELECT COUNT(*) FROM Customer" txtcount.text = MyCommand.ExecuteScalar() Using parameters in the SQL statement The Command Class has a property named Parameters. It is a collection for holding all parameters and their values relevant to the particular command. The values of the parameters are added to the collection with using the parameter name as their key values. The parameter is indicated by sign. MyCommand.Parameters.Add("@CustID", txtcustid.text) The SQL command is written by using the parameter names in the places, where the actual values are used when the command is executed. MyCommand.CommandText = _ "INSERT INTO Customer(CustID, Name) VALUES Example: Insert the user given values into the Customer table. MyCommand.Connection = MyConnection 'Add values to the Parameter collection of the Command object MyCommand.Parameters.Add("@CustID", txtcustid.text) MyCommand.Parameters.Add("@Name", txtname.text) MyCommand.Parameters.Add("@Area", txtarea.text) MyCommand.Parameters.Add("@Balance", txtbalance.text) 'Write the SQL statement for the Command object by using parameters MyCommand.CommandText = _ "INSERT INTO Customer(CustID, Name, Area, Balance )" & _ @Balance)" 'Execute the statement MyConnection.Open() MyCommand.ExecuteNonQuery() MyConnection.Close()

104 21. Using DataAdapter and DataSet.NET supports handling of disconnected data. This is good for example in handling large amount of data or data, which is stored behind insecure or restricted connections. The idea is to fetch the desired data from the database, store it locally in the memory and to handle the data there. After finishing with handling the data, the new information is saved into the database Loading data into the local memory For moving the data between the database and the memory,.net offers an object called DataAdapter. It serves as a bridge between the memory and the data source. DataAdapter has a SelectCommand property, which holds in its CommandText property a SQL select statement for determining what data shall be retrieved from the data source into the local memory. The SelectCommand is activated when calling the Fill method of the DataAdapter. The Fill method fetches the desired data from the database and places it into a DataSet object. The DataSet consists of a collection of DataTable objects. Connection Connection- String Command CommandText = "SELECT " Connection DataAdapter SelectCommand Fill() Database: C:\DBFile.mdb DataSet MyCustomer CustID Name MyOrders CustID ProdID Qty Price Example: Fetch customer ids and names from the database and place them in a DataSet. 'Define the connection to the database and open it Dim MyConnection As New OleDbConnection() MyConnection.ConnectionString = _ "Provider=Microsoft.Jet.OLEDB.4.0; _ Data Source=c:\databases\CustomerOrders.mdb;" MyConnection.Open() MyConnection DB

105 'Define the Data adapter and its SelectCommand property Dim MyDataAdapter As New OleDbDataAdapter() MyDataAdapter.SelectCommand = New OleDbCommand() MyDataAdapter.SelectCommand.CommandText = _ "SELECT CustID, Name FROM Customer" MyDataAdapter.SelectCommand.Connection = MyConnection MyConnection DB Command CommandText = "SELECT " Connection MyDataAdapter SelectCommand 'Define a DataSet and use the data adapter to fill the DataSet 'with the customers. Give a name (as "MyCustomer") for the table for 'referring to it later in the DataSet. Dim MyDataSet As New DataSet() MyDataAdapter.Fill(MyDataSet, "MyCustomer") MyConnection DB Command CommandText = "SELECT " Connection MyDataAdapter SelectCommand Fill() MyDataSet MyCustomer CustID Name 13 Jane 14 John 15 Mark 'Close the connection MyConnection.Close()

106 21.2. DataSet object A DataSet object is a lot like a mini database engine, but its data exists in memory. Besides holding the data, the DataSet object stores metadata (data about the data) like table and column names. Example 1: The DataSet object holds all the tables as DataTable objects in a collection, which is a property named Tables. An individual table in the collection can be referred by the name of the table given when filling the DataSet: MyDataSet.Tables("MyCustomer") The DataTable object holds all the rows that belong to it as DataRow objects in a collection named Rows. One row can be referred by the index of the row in question: MyDataSet.Tables("MyCustomer").Rows(2) The actual data is stored in an Item object. The data in a single cell can be referred by the name of the column: MyDataSet.Tables("MyCustomer").Rows(2).Item("Name") MyDataSet MyCustomer CustID Name 13 Jane 14 John 15 Mark 16 Lisa Example 2: Add the customer names into a list box named ListBox1. Below there are three different ways of doing it: 'A: Use the For statement to loop through rows in the Tables property Dim i As Integer For i = 0 To MyDataSet.Tables("MyCustomer").Rows.Count - 1 ListBox1.Items.Add( _ MyDataSet.Tables("MyCustomer").Rows(i).Item("Name")) Next 'B: Add a With statement to the solution A to make ' the solution more clear With MyDataSet.Tables("MyCustomer") Dim i As Integer For i = 0 To.Rows.Count - 1 ListBox1.Items.Add(.Rows(i).Item("Name")) Next End With

107 'C: Change the solution B to use the For Each loop ' instead of the 'classic' For loop With MyDataSet.Tables("MyCustomer") Dim CustomerRow As DataRow For Each CustomerRow In.Rows ListBox1.Items.Add(CustomerRow.Item("Name")) Next End With Showing DataSet data on Windows form using the DataGridView control A DataGridView control is a control that is used to display data tables much like what we see when we execute the results of our query in Access. In order to display the data, the DataGrid- View control needs to be bound to a DataSet. When a control is bound to a data source, the data is automatically displayed in the control for the user to see and manipulate. There are two main properties in the DataGridView control, which must be set in order to bind a DataSet component to it. These are the DataSource and DataMember properties. The DataSource property is used for specifying the source of the data (a DataSet), to which the DataGridView will be bound. If a DataSet contains more than one table, also the DataMember property needs to be set. The value of the DataMember property is a string that specifies the name of table to which the DataGridView shall be bound. 'Let's assume that the data has been fetched to the DataSet MyDataSet 'as shown in the example above. Setting the values of the DataSource 'and DataMember properties will bind the data of the DataSet 'to the DataGridView named MyDataGridView MyDataGridView.DataSource = MyDataSet MyDataGridView.DataMember = "MyCustomer" MyDataSet MyCustomer CustID Name 13 Jane 14 John 15 Mark 16 Lisa 'The DataGridView control has a property CurrentRow.Index that holds 'the index of the currently selected row. The index corresponds 'straight with the index of the Rows collection of a DataTable. TextBox1.Text = MyDataSet.Tables("MyCustomer"). _ Rows(MyDataGridView.CurrentRow.Index).Item("Name")

108 21.4. Selecting rows and columns from a DataTable Selecting rows A DataView is an object that works as a filter for choosing rows from a DataTable. The RowFilter property is used to store the selection criteria. Dim MyDataView As New DataView(MyDataSet.Tables("MyCustomer")) MyDataView.RowFilter = "Balance > 100" 'The selected rows can be listed in a Grid MyDataGridView.DataSource = MyDataView Selecting columns When selecting columns, one has to create new DataTable based on the original data table as a source table. Make the copy as follows: Dim MyDataTable As DataTable Dim MyDataView As New DataView(MyDataSet.Tables("MyCustomer")) 'Set the list of columns into an string array Dim columns() As String = {"CustID", "Name"} 'Public Function ToTable(ByVal distinct As Boolean, ' ByVal columnnames As String()) As DataTable 'distinct: If true, the returned DataTable contains rows that have ' distinct values for all its columns. ' The default value is false. MyDataTable = MyDataView.ToTable(False, columns) 'Show on the Grid MyDataGridView.DataSource = MyDataTable Note that the changes are made into the copy of the table, not the original one.

109 22. Relations in a DataSet A DataSet can hold multiple tables at the same time. The DataTable objects are collected in the DataSet object s Tables property. Besides of holding multiple tables, DataSet object has a property named Relations for holding information of relations between its tables. The relations are defined in VB.NET as DataRelation objects Creating relations Two tables are related to each other through their key columns. In VB.NET a relation is constructed by creating a DataRelation object and defining its parent column and child column properties to point to the key columns of the tables to be related. DataRelation Name ParentColumn ChildColumn DataSet MyCustomer CustID Name MyOrders CustID ProdID Qty Pri When a DataRelation object is constructed, it is given a string value for its Name property and a DataColumn object of both of the DataTable objects being part of the relation. The other DataColumn is defined as a parent column and the other one as a child column, depending on the nature of the relationship. This is similar to a primary key / foreign key relationship. After creating the DataRelation, it is added to the Relations collection of the corresponding DataSet. 'Define the parent and child columns Dim parentcol, childcol As DataColumn parentcol = MyDataSet.Tables("MyCustomer").Columns("CustID") childcol = MyDataSet.Tables("MyOrders").Columns("CustID") 'Define the DataRelation object Dim relcustorder As DataRelation relcustorder = _ New DataRelation("CustomerOrders", parentcol, childcol) 'Add the relation to the DataSet MyDataSet.Relations.Add(relCustOrder)

110 22.2. Using relations One of the primary functions of the DataRelation object is to allow navigation from one DataTable to another within a DataSet. This allows one to retrieve all the related DataRow objects in one DataTable when given a single DataRow from a related DataTable Fetching the ChildRows For example, after establishing a DataRelation between a table of customers and a table of orders (as in the example above), one can retrieve all the order rows for a particular customer row by using the DataRow.GetChildRows method. Dim custrow, orderrow As DataRow custrow = MyDataSet.Tables("MyCustomer").Rows(1) For Each orderrow In custrow.getchildrows("customerorders") TextBox1.AppendText(orderRow("ProdID") & ControlChars.NewLine) Next Fetching the ParentRow Correspondingly as getting the child rows of a data row in a parent table, a parent row of a data row in a child table can be fetched through the relation by using the DataRow.GetParentRow method. Example: Get the name of the customer of a certain order. Dim custrow, orderrow As DataRow orderrow = MyDataSet.Tables("MyOrders"). _ Rows(DataGridView1.CurrentRow.Index) custrow = orderrow.getparentrow("customerorders") TextBox1.Text = custrow("name") The effect of relationships on the DataGridView control If the DataSource of a DataGridView control is set to a DataSet that contains DataRelation objects, parent tables will appear with a plus sign (+) in each row header. Clicking the plus sign causes a node to appear that contains links to child tables. When clicking the link, one can navigate to the child table.

111 'In the code the binding between the DataSet and the DataGridView 'happens exactly the same way as before. The programmer 'doesn t have to take care of the existent of probable relations DataGridView1.DataSource = MyDataSet DataGridView1.DataMember = "MyCustomer" Example Fetch all the data from tables customer and orders into the DataSet, create a relationship between those two tables and show the data on a Windows form by using the DataGridView control. 'Define the data objects needed Dim MyConnection As New OleDbConnection() Dim MyDataAdapter As New OleDbDataAdapter() Dim MyDataSet As New DataSet() Dim parentcol, childcol As DataColumn Dim relcustorder As DataRelation 'Define the target (data source) of the connection MyConnection.ConnectionString = _ "Provider=Microsoft.Jet.OLEDB.4.0; _ Data Source=c:\databases\CustomerOrders.mdb;" 'Define the SelectCommand of the data adapter MyDataAdapter.SelectCommand = New OleDbCommand() MyDataAdapter.SelectCommand.CommandText = _ "SELECT * FROM Customer" MyDataAdapter.SelectCommand.Connection = MyConnection 'Open the connection MyConnection.Open() 'Fill the DataSet with the customers information MyDataAdapter.Fill(MyDataSet, "MyCustomer") 'Fill the DataSet with the orders information MyDataAdapter.SelectCommand.CommandText = "SELECT * FROM Orders" MyDataAdapter.Fill(MyDataSet, "MyOrders") 'Close the connection MyConnection.Close() 'Define the parent and child columns parentcol = MyDataSet.Tables("MyCustomer").Columns("CustID") childcol = MyDataSet.Tables("MyOrders").Columns("CustID") 'Create the DataRelation relcustorder = _ New DataRelation("CustomerOrders", parentcol, childcol) 'Add the relation to the DataSet MyDataSet.Relations.Add(relCustOrder) 'Display the DataSet in the DataGridView DataGridView1.DataSource = MyDataSet DataGridView1.DataMember = "MyCustomer"

112 23. Updating database using DataAdapter The idea of updating a database using a data adapter is that the data adapter examines the changes (update, insert and delete) made in the dataset and then performs the appropriate commands to process the changes. In the program it happens as follows: 1. The application calls the Update method of the DataAdapter. 2. The DataAdapter automatically a. analyzes the changes that have been made to the dataset to a certain table and then b. executes the required insert, update or delete statements iteratively for each row using the commands, which are set to it s command properties. Connection ConnectionString Database: C:\DBFile.mdb Command CommandText = "UPDATE " Connection Command CommandText = "INSERT " Connection Command CommandText = "DELETE " Connection DataAdapter UpdateCommand InsertCommand DeleteCommand Update() DataSet MyCustomer CustID Name MyOrders CustID ProdID Qty Price DataAdapter s Update method The Update method of the DataAdapter is called to update the changes from a DataSet back to the data source. The Update method takes as its arguments an instance of a DataSet and the given name (string) of a DataTable. It returns the number of rows successfully updated. Dim NumberOfRowsUpdated As Integer NumberOfRowsUpdated = MyDataAdapter.Update(MyDataSet, "MyCustomer") When an application calls the Update method, the DataAdapter examines the data of the defined table in the dataset row by row. When it encounters a change in a DataRow, it uses the InsertCommand, UpdateCommand or DeleteCommand object to process the change. The Command objects need to be set explicitly before calling Update method.

113 23.2. Setting the non query commands for a data adapter The DataAdapter s non query commands need to be written in a special way: 1. One command needs to perform action for several rows; thereby the statements need to be written in a general form. It means, that no constant values can be written ready in the statement. Example: The general form of the insert statement could be as follows: INSERT INTO Customer( CustID, Name, Area, Balance ) VALUES (?,?,?,? ) 2. The other thing to consider is the concurrency (samanaikaisuus). On the other words, the data in the database could have been modified by someone else after it was fetched to the dataset, but before the update takes place. Example: The general form of an update statement that takes care of the concurrency could be as follows: UPDATE Customer SET CustID =?, Name =?, Area =?, Balance =? WHERE ( (CustID =?) AND ((? IS NULL AND Name IS NULL) OR (Name =?)) AND ((? IS NULL AND Area IS NULL) OR (Area =?)) AND ((? IS NULL AND Balance IS NULL) OR (Balance =?)) ) The command is a little bit complicated. That s why VB.NET offers a helper object, CommandBuilder, for creating these commands CommandBuilder object The CommandBuilder object generates automatically the DeleteCommand, InsertCommand and UpdateCommand objects for the DataAdapter object, to which its DataAdapter property is pointing to. The CommandBuilder generates them by using the SelectCommand property of the DataAdapter object. So, the requirement for using the CommandBuilder is that the DataAdapter s SelectCommand property exists and that it s CommandText property contains an appropriate SQL statement. CommandBuilder DataAdapter DataAdapter SelectCommand Command CommandText = "SELECT "

114 To automatically generate the non query SQL statements for a DataAdapter: 1. Set the SelectCommand property for the DataAdapter 2. Create a CommandBuilder object and assign its DataAdapter property value to be that particular DataAdapter object for which the non query commands shall be generated. 'Set the SelectCommand property for the DataAdapter MyDataAdapter.SelectCommand = New OleDbCommand() MyDataAdapter.SelectCommand.CommandText = _ "SELECT CustID, Name FROM Customer" 'Create a CommandBuilder object and assign MyDataAdapter 'to be the value of its DataAdapter property Dim MyCommandBuilder As New OleDbCommandBuilder() MyCommandBuilder.DataAdapter = MyDataAdapter When the SelectCommand value of the OleDbDataAdapter changes, the commands generated by the CommandBuilder, should also be changed. That is easily done by calling the RefreshSchema method of the CommandBuilder object. Example: This example continues the code from the previous example by creating a new select statement for fetching data from the Customer table, to include the Balance field. MyDataAdapter.SelectCommand.CommandText = _ "SELECT CustID, Name, Balance FROM Customer" 'Now the automatically generated commands need to be refreshed 'to correspond the new schema of the table: MyCommandBuilder.RefreshSchema() Summary To update a database with the data in a data set: 1. Make sure that the DataAdapter has a SelectCommand, which corresponds with the table (in the dataset) that shall be updated. 2. Create the non query commands for the DataAdapter by using a CommandBuilder object. If the commands already have been created, refresh (if needed) the commands to correspond that table in the dataset, which shall be updated. 3. Update the database using the Update method of the DataAdapter Example This program fetches customers from a database into a DataGridView control and lets the user to make changes. The cmdupdate Button updates the Customer table back to the database. Dim MyConnection As New OleDbConnection() Dim MyDataAdapter As New OleDbDataAdapter() Dim MyDataSet As New DataSet() Private Sub btnfetchcustomers_click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _ btnfetchcustomers Button1.Click

115 'Define the connection to the database and open it MyConnection.ConnectionString = _ "Provider=Microsoft.Jet.OLEDB.4.0; Data _ Source=..\..\CustomerOrders.mdb;" MyDataAdapter.SelectCommand = New OleDbCommand() MyDataAdapter.SelectCommand.CommandText = _ "SELECT CustID, Name, Balance FROM Customer" MyDataAdapter.SelectCommand.Connection = MyConnection 'Now create command objects for the INSERT,UPDATE,DELETE 'commands Dim mycommandbuilder As New OleDbCommandBuilder(MyDataAdapter) 'Get the rows from the database into dataset. MyDataAdapter.Fill(MyDataSet, "MyCustomer") 'Show the rows in DataGridView mydatagridview.datasource = mydataset mydatagridview.datamember = "MyCustomer" Private Sub btnupdate_click _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btnupdate.click MyDataAdapter.Update(MyDataSet, "MyCustomer")

116 24. Using the dataset programmatically As mentioned before, a dataset is like a mini database engine, whose data exists in memory. A dataset can be manipulated similarly as a database is manipulated with queries. It means that rows matching a given criteria can be selected, new rows can be inserted and existing rows can be updated or deleted in tables in a dataset Selecting rows The desired rows from a certain table in a dataset are selected using the Select property of the DataTable. When calling the Select property, it is passed criteria as a parameter. The criteria are used as a filter, when selecting the matching rows from the DataTable. The return value is an array of DataRow objects. Dim strcriteria As String Dim foundcustomers() As DataRow strcriteria = "Balance > 1000" foundcustomers = MyDataSet.Tables("MyCustomer").Select(strCriteria) If you want to allow the user to select the rows you can use the SelectedRows property value of DataGridView control. The following example shows the names of the customers selected. For i = 0 To DataGridView1.SelectedRows.Count 1 MessageBox.Show( _ DataGridView1.SelectedRows.Item(i).Cells("Name").Value) Next Inserting rows To insert a new row into a table in a dataset, the row must be created first. That happens by calling the NewRow method of the DataTable object, which returns a new DataRow object with the same structure as the previous rows of it have. After creating the DataRow object and setting the values for each of its columns, the row is added to the Rows collection of the corresponding DataTable using the Rows collection s Add method. Example: Insert a new customer into the MyCustomer table in the MyDataSet dataset. Get the values for the customer from text boxes given by the end-user. MyDataSet MyCustomer CustID Name Area Balance 13 Jane South John North Mark East Lisa West 150 'Create a row that has the same structure as the MyCustomer table Dim customerrow As DataRow customerrow = MyDataSet.Tables("MyCustomer").NewRow

1 Dept: CE.NET Programming ( ) Prof. Akash N. Siddhpura. Working with Form: properties, methods and events

1 Dept: CE.NET Programming ( ) Prof. Akash N. Siddhpura. Working with Form: properties, methods and events Working with Form: properties, methods and events To create a New Window Forms Application, Select File New Project. It will open one dialog box which is shown in Fig 2.1. Fig 2.1 The New Project dialog

More information

Visual BASIC Creating an Application. Choose File New Project from the menu

Visual BASIC Creating an Application. Choose File New Project from the menu Creating an Application Choose File New Project from the menu Choose Windows Application Name the project Copyright Project Place a check in the Create directory for solution box Click Browse Choose and/or

More information

CST242 Windows Forms with C# Page 1

CST242 Windows Forms with C# Page 1 CST242 Windows Forms with C# Page 1 1 2 4 5 6 7 9 10 Windows Forms with C# CST242 Visual C# Windows Forms Applications A user interface that is designed for running Windows-based Desktop applications A

More information

Visual C# Program: Simple Game 3

Visual C# Program: Simple Game 3 C h a p t e r 6C Visual C# Program: Simple Game 3 In this chapter, you will learn how to use the following Visual C# Application functions to World Class standards: Opening Visual C# Editor Beginning a

More information

Using Visual Basic Studio 2008

Using Visual Basic Studio 2008 Using Visual Basic Studio 2008 Recall that object-oriented programming language is a programming language that allows the programmer to use objects to accomplish a program s goal. An object is anything

More information

Final Exam 7:00-10:00pm, April 14, 2008

Final Exam 7:00-10:00pm, April 14, 2008 Name:, (last) (first) Student Number: Section: Instructor: _P. Cribb_ L. Lowther_(circle) York University Faculty of Science and Engineering Department of Computer Science and Engineering Final Exam 7:00-10:00pm,

More information

Visual Basic.NET. 1. Which language is not a true object-oriented programming language?

Visual Basic.NET. 1. Which language is not a true object-oriented programming language? Visual Basic.NET Objective Type Questions 1. Which language is not a true object-oriented programming language? a.) VB.NET b.) VB 6 c.) C++ d.) Java Answer: b 2. A GUI: a.) uses buttons, menus, and icons.

More information

Unit 3. Lesson Designing User Interface-2. TreeView Control. TreeView Contol

Unit 3. Lesson Designing User Interface-2. TreeView Control. TreeView Contol Designing User Interface-2 Unit 3 Designing User Interface-2 Lesson 3.1-3 TreeView Control A TreeView control is designed to present a list in a hierarchical structure. It is similar to a directory listing.

More information

Efficiency of Bubble and Shell Sorts

Efficiency of Bubble and Shell Sorts REVIEW Efficiency of Bubble and Shell Sorts Array Elements Bubble Sort Comparisons Shell Sort Comparisons 5 10 17 10 45 57 15 105 115 20 190 192 25 300 302 30 435 364 50 1225 926 100 4950 2638 500 124,750

More information

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals VARIABLES WHAT IS A VARIABLE? A variable is a storage location in the computer s memory, used for holding information while the program is running. The information that is stored in a variable may change,

More information

Tutorial 03 understanding controls : buttons, text boxes

Tutorial 03 understanding controls : buttons, text boxes Learning VB.Net Tutorial 03 understanding controls : buttons, text boxes Hello everyone welcome to vb.net tutorials. These are going to be very basic tutorials about using the language to create simple

More information

How to Use MessageBox

How to Use MessageBox How to Use MessageBox Contents MessageBox Class... 1 Use MessageBox without checking result... 4 Check MessageBox Return Value... 8 Use a property to save MessageBox return... 9 Check MessageBox return

More information

Learning VB.Net. Tutorial 17 Classes

Learning VB.Net. Tutorial 17 Classes Learning VB.Net Tutorial 17 Classes Hello everyone welcome to vb.net tutorials. These are going to be very basic tutorials about using the language to create simple applications, hope you enjoy it. If

More information

Your First Windows Form

Your First Windows Form Your First Windows Form From now on, we re going to be creating Windows Forms Applications, rather than Console Applications. Windows Forms Applications make use of something called a Form. The Form is

More information

Recommended GUI Design Standards

Recommended GUI Design Standards Recommended GUI Design Standards Page 1 Layout and Organization of Your User Interface Organize the user interface so that the information follows either vertically or horizontally, with the most important

More information

Additional Controls & Objects

Additional Controls & Objects Additional Controls & Objects November 8, 2006 Chapter 9 - VB 2005 by Schneider 1 General Tips & Tricks Now is the time to start thinking about the final exam Continue (start!) doing questions from the

More information

Program and Graphical User Interface Design

Program and Graphical User Interface Design CHAPTER 2 Program and Graphical User Interface Design OBJECTIVES You will have mastered the material in this chapter when you can: Open and close Visual Studio 2010 Create a Visual Basic 2010 Windows Application

More information

COPYRIGHTED MATERIAL. Visual Basic: The Language. Part 1

COPYRIGHTED MATERIAL. Visual Basic: The Language. Part 1 Part 1 Visual Basic: The Language Chapter 1: Getting Started with Visual Basic 2010 Chapter 2: Handling Data Chapter 3: Visual Basic Programming Essentials COPYRIGHTED MATERIAL Chapter 1 Getting Started

More information

Lecture 5 COMMON CONTROLS

Lecture 5 COMMON CONTROLS Lecture 5 COMMON CONTROLS 1. The ListBox Class Represents a box that contains a list of items. The following are its some of its more important properties: MultiColumn This is a Boolean that indicates

More information

Unit 3 Additional controls and Menus of Windows

Unit 3 Additional controls and Menus of Windows Working with other controls of toolbox: DateTime Picker If you want to enable users to select a date and time, and to display that date and time in the specified format, use the DateTimePicker control.

More information

Overview About KBasic

Overview About KBasic Overview About KBasic The following chapter has been used from Wikipedia entry about BASIC and is licensed under the GNU Free Documentation License. Table of Contents Object-Oriented...2 Event-Driven...2

More information

GUI Design and Event- Driven Programming

GUI Design and Event- Driven Programming 4349Book.fm Page 1 Friday, December 16, 2005 1:33 AM Part 1 GUI Design and Event- Driven Programming This Section: Chapter 1: Getting Started with Visual Basic 2005 Chapter 2: Visual Basic: The Language

More information

Programming. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Programming. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies 9 Programming Based on Events C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Create applications that use

More information

Chapter 2. Creating Applications with Visual Basic Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of

Chapter 2. Creating Applications with Visual Basic Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 2 Creating Applications with Visual Basic Addison Wesley is an imprint of 2011 Pearson Addison-Wesley. All rights reserved. Section 2.1 FOCUS ON PROBLEM SOLVING: BUILDING THE DIRECTIONS APPLICATION

More information

Introductionto the Visual Basic Express 2008 IDE

Introductionto the Visual Basic Express 2008 IDE 2 Seeing is believing. Proverb Form ever follows function. Louis Henri Sullivan Intelligence is the faculty of making artificial objects, especially tools to make tools. Henri-Louis Bergson Introductionto

More information

Visual C# Program: Resistor Sizing Calculator

Visual C# Program: Resistor Sizing Calculator C h a p t e r 4 Visual C# Program: Resistor Sizing Calculator In this chapter, you will learn how to use the following Visual C# Application functions to World Class standards: Opening Visual C# Editor

More information

HOUR 4 Understanding Events

HOUR 4 Understanding Events HOUR 4 Understanding Events It s fairly easy to produce an attractive interface for an application using Visual Basic.NET s integrated design tools. You can create beautiful forms that have buttons to

More information

Lab 3 The High-Low Game

Lab 3 The High-Low Game Lab 3 The High-Low Game LAB GOALS To develop a simple windows-based game named High-Low using VB.Net. You will use: Buttons, Textboxes, Labels, Dim, integer, arithmetic operations, conditionals [if-then-else],

More information

Graphical User Interface Canvas Frame Event structure Platform-free GUI operations Operator << Operator >> Operator = Operator ~ Operator + Operator

Graphical User Interface Canvas Frame Event structure Platform-free GUI operations Operator << Operator >> Operator = Operator ~ Operator + Operator Graphical User Interface Canvas Frame Event structure Platform-free GUI operations Operator > Operator = Operator ~ Operator + Operator - Operator [] Operator size Operator $ Operator? Operator!

More information

Visual Basic 2008 Anne Boehm

Visual Basic 2008 Anne Boehm TRAINING & REFERENCE murach s Visual Basic 2008 Anne Boehm (Chapter 3) Thanks for downloading this chapter from Murach s Visual Basic 2008. We hope it will show you how easy it is to learn from any Murach

More information

(0,0) (600, 400) CS109. PictureBox and Timer Controls

(0,0) (600, 400) CS109. PictureBox and Timer Controls CS109 PictureBox and Timer Controls Let s take a little diversion and discuss how to draw some simple graphics. Graphics are not covered in the book, so you ll have to use these notes (or the built-in

More information

Windows 7 Control Pack for WinForms

Windows 7 Control Pack for WinForms ComponentOne Windows 7 Control Pack for WinForms By GrapeCity, Inc. Copyright 1987-2012 GrapeCity, Inc. All rights reserved. Corporate Headquarters ComponentOne, a division of GrapeCity 201 South Highland

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Full file at https://fratstock.eu Programming in Visual Basic 2010

Full file at https://fratstock.eu Programming in Visual Basic 2010 OBJECTIVES: Chapter 2 User Interface Design Upon completion of this chapter, your students will be able to 1. Use text boxes, masked text boxes, rich text boxes, group boxes, check boxes, radio buttons,

More information

Visual C# Program: Temperature Conversion Program

Visual C# Program: Temperature Conversion Program C h a p t e r 4B Addendum Visual C# Program: Temperature Conversion Program In this chapter, you will learn how to use the following Visual C# Application functions to World Class standards: Writing a

More information

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013 GETTING STARTED PAGE 02 Prerequisites What You Will Learn MORE TASKS IN MICROSOFT EXCEL PAGE 03 Cutting, Copying, and Pasting Data Basic Formulas Filling Data

More information

Text box. Command button. 1. Click the tool for the control you choose to draw in this case, the text box.

Text box. Command button. 1. Click the tool for the control you choose to draw in this case, the text box. Visual Basic Concepts Hello, Visual Basic See Also There are three main steps to creating an application in Visual Basic: 1. Create the interface. 2. Set properties. 3. Write code. To see how this is done,

More information

Menus, Common Dialog Controls, Context Menus, Sub Procedures, and Functions

Menus, Common Dialog Controls, Context Menus, Sub Procedures, and Functions 5-menus.htm; updated September 12, 2011 Menus, Common Dialog Controls, Context Menus, Sub Procedures, and Functions Coverage: This chapter covers several important topics: (1) use of menus and context

More information

OCTAVO An Object Oriented GUI Framework

OCTAVO An Object Oriented GUI Framework OCTAVO An Object Oriented GUI Framework Federico de Ceballos Universidad de Cantabria federico.ceballos@unican.es November, 2004 Abstract This paper presents a framework for building Window applications

More information

NiceForm User Guide. English Edition. Rev Euro Plus d.o.o. & Niceware International LLC All rights reserved.

NiceForm User Guide. English Edition. Rev Euro Plus d.o.o. & Niceware International LLC All rights reserved. www.nicelabel.com, info@nicelabel.com English Edition Rev-0910 2009 Euro Plus d.o.o. & Niceware International LLC All rights reserved. www.nicelabel.com Head Office Euro Plus d.o.o. Ulica Lojzeta Hrovata

More information

Keeping Track, Menus. CSC 330 Object-Oriented Programming 1

Keeping Track, Menus. CSC 330 Object-Oriented Programming 1 Keeping Track, Menus CSC 330 Object-Oriented Programming 1 Chapter Objectives Keeping Track Create menus and submenus for program control Display and use the Windows common dialog boxes Create context

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel Formatting a spreadsheet means changing the way it looks to make it neater and more attractive. Formatting changes can include modifying number styles, text size and colours. Many

More information

Location of menu elements

Location of menu elements E Creating Menus Appendix E C5779 39147 Page 1 07/10/06--JHR In Visual Basic 2005, you use a MenuStrip control to include one or more menus in an application. You instantiate a MenuStrip control using

More information

The Fundamentals. Document Basics

The Fundamentals. Document Basics 3 The Fundamentals Opening a Program... 3 Similarities in All Programs... 3 It's On Now What?...4 Making things easier to see.. 4 Adjusting Text Size.....4 My Computer. 4 Control Panel... 5 Accessibility

More information

Visual Basic Program Coding STEP 2

Visual Basic Program Coding STEP 2 Visual Basic Program Coding 129 STEP 2 Click the Start Debugging button on the Standard toolbar. The program is compiled and saved, and then is run on the computer. When the program runs, the Hotel Room

More information

Mr.Khaled Anwar ( )

Mr.Khaled Anwar ( ) The Rnd() function generates random numbers. Every time Rnd() is executed, it returns a different random fraction (greater than or equal to 0 and less than 1). If you end execution and run the program

More information

Dive Into Visual C# 2010 Express

Dive Into Visual C# 2010 Express Dive Into Visual C# 2010 Express 2 Seeing is believing. Proverb Form ever follows function. Louis Henri Sullivan Intelligence is the faculty of making artificial objects, especially tools to make tools.

More information

Visual Programming 1. What is Visual Basic? 2. What are different Editions available in VB? 3. List the various features of VB

Visual Programming 1. What is Visual Basic? 2. What are different Editions available in VB? 3. List the various features of VB Visual Programming 1. What is Visual Basic? Visual Basic is a powerful application development toolkit developed by John Kemeny and Thomas Kurtz. It is a Microsoft Windows Programming language. Visual

More information

variables programming statements

variables programming statements 1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual

More information

Use Default Form Instances

Use Default Form Instances Use Default Form Instances Created: 2011-01-03 Modified:2012-07-05 Contents Introduction... 2 Add Form Classes... 3 Starting Form (Home Page)... 5 Use Multiple Forms... 6 Different Ways of Showing Forms...

More information

Introduction to Data Entry and Data Types

Introduction to Data Entry and Data Types 212 Chapter 4 Variables and Arithmetic Operations STEP 1 With the Toolbox visible (see Figure 4-21), click the Toolbox Close button. The Toolbox closes and the work area expands in size.to reshow the Toolbox

More information

LESSON B. The Toolbox Window

LESSON B. The Toolbox Window The Toolbox Window After studying Lesson B, you should be able to: Add a control to a form Set the properties of a label, picture box, and button control Select multiple controls Center controls on the

More information

Forms for Android Version Manual. Revision Date 12/7/2013. HanDBase is a Registered Trademark of DDH Software, Inc.

Forms for Android Version Manual. Revision Date 12/7/2013. HanDBase is a Registered Trademark of DDH Software, Inc. Forms for Android Version 4.6.300 Manual Revision Date 12/7/2013 HanDBase is a Registered Trademark of DDH Software, Inc. All information contained in this manual and all software applications mentioned

More information

Spreadsheet View and Basic Statistics Concepts

Spreadsheet View and Basic Statistics Concepts Spreadsheet View and Basic Statistics Concepts GeoGebra 3.2 Workshop Handout 9 Judith and Markus Hohenwarter www.geogebra.org Table of Contents 1. Introduction to GeoGebra s Spreadsheet View 2 2. Record

More information

Object Oriented Programming with Visual Basic.Net

Object Oriented Programming with Visual Basic.Net Object Oriented Programming with Visual Basic.Net By: Dr. Hossein Hakimzadeh Computer Science and Informatics IU South Bend (c) Copyright 2007 to 2015 H. Hakimzadeh 1 What do we need to learn in order

More information

WinForms Applications

WinForms Applications Agenda WinForms Applications Writing native Windows programs Tuesday, November 2, 2004 1 PWindows Applications PEvents and event handlers PLayered (tiered) model of software PFocus PForm designer and controls

More information

Table Basics. The structure of an table

Table Basics. The structure of an table TABLE -FRAMESET Table Basics A table is a grid of rows and columns that intersect to form cells. Two different types of cells exist: Table cell that contains data, is created with the A cell that

More information

Introduction to Microsoft Excel 2010

Introduction to Microsoft Excel 2010 Introduction to Microsoft Excel 2010 This class is designed to cover the following basics: What you can do with Excel Excel Ribbon Moving and selecting cells Formatting cells Adding Worksheets, Rows and

More information

Advanced Microsoft Word 2010

Advanced Microsoft Word 2010 Advanced Microsoft Word 2010 WordArt WordArt gives your letters special effects. You can change the formatting, direction, and texture of your text by adding WordArt. When you click the WordArt icon on

More information

Excel Select a template category in the Office.com Templates section. 5. Click the Download button.

Excel Select a template category in the Office.com Templates section. 5. Click the Download button. Microsoft QUICK Excel 2010 Source Getting Started The Excel Window u v w z Creating a New Blank Workbook 2. Select New in the left pane. 3. Select the Blank workbook template in the Available Templates

More information

DEVELOPING DATABASE APPLICATIONS (INTERMEDIATE MICROSOFT ACCESS, X405.5)

DEVELOPING DATABASE APPLICATIONS (INTERMEDIATE MICROSOFT ACCESS, X405.5) Technology & Information Management Instructor: Michael Kremer, Ph.D. Database Program: Microsoft Access Series DEVELOPING DATABASE APPLICATIONS (INTERMEDIATE MICROSOFT ACCESS, X405.5) Section 5 AGENDA

More information

Stamina Software Pty Ltd. TRAINING MANUAL Viságe BIT VIEWER

Stamina Software Pty Ltd. TRAINING MANUAL Viságe BIT VIEWER Stamina Software Pty Ltd TRAINING MANUAL Viságe BIT VIEWER Version: 3 31 st October 2011 Viságe BIT Viewer TABLE OF CONTENTS VISÁGE BIT VIEWER... 2 ELEMENTS OF THE VISÁGE BIT VIEWER SCREEN... 3 TITLE...

More information

Visual Basic 2008 The programming part

Visual Basic 2008 The programming part Visual Basic 2008 The programming part Code Computer applications are built by giving instructions to the computer. In programming, the instructions are called statements, and all of the statements that

More information

Microsoft Visual Basic 2005 CHAPTER 5. Mobile Applications Using Decision Structures

Microsoft Visual Basic 2005 CHAPTER 5. Mobile Applications Using Decision Structures Microsoft Visual Basic 2005 CHAPTER 5 Mobile Applications Using Decision Structures Objectives Write programs for devices other than a personal computer Understand the use of handheld technology Write

More information

Philadelphia University Faculty of Information Technology. Visual Programming

Philadelphia University Faculty of Information Technology. Visual Programming Philadelphia University Faculty of Information Technology Visual Programming Using C# -Work Sheets- Prepared by: Dareen Hamoudeh Eman Al Naji Work Sheet 1 Form, Buttons and labels Properties Changing properties

More information

Introduction to Microsoft Excel 2010

Introduction to Microsoft Excel 2010 Introduction to Microsoft Excel 2010 This class is designed to cover the following basics: What you can do with Excel Excel Ribbon Moving and selecting cells Formatting cells Adding Worksheets, Rows and

More information

Understanding Word Processing

Understanding Word Processing Understanding Word Processing 3.0 Introduction In this chapter you are going to learn how to create a simple memo or note or a complex and complicated multi column business document using word processing

More information

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array?

Programming with Microsoft Visual Basic.NET. Array. What have we learnt in last lesson? What is Array? What have we learnt in last lesson? Programming with Microsoft Visual Basic.NET Using Toolbar in Windows Form. Using Tab Control to separate information into different tab page Storage hierarchy information

More information

HYPERSTUDIO TOOLS. THE GRAPHIC TOOL Use this tool to select graphics to edit. SPRAY PAINT CAN Scatter lots of tiny dots with this tool.

HYPERSTUDIO TOOLS. THE GRAPHIC TOOL Use this tool to select graphics to edit. SPRAY PAINT CAN Scatter lots of tiny dots with this tool. THE BROWSE TOOL Us it to go through the stack and click on buttons THE BUTTON TOOL Use this tool to select buttons to edit.. RECTANGLE TOOL This tool lets you capture a rectangular area to copy, cut, move,

More information

GUJARAT TECHNOLOGICAL UNIVERSITY DIPLOMA IN INFORMATION TECHNOLOGY Semester: 4

GUJARAT TECHNOLOGICAL UNIVERSITY DIPLOMA IN INFORMATION TECHNOLOGY Semester: 4 GUJARAT TECHNOLOGICAL UNIVERSITY DIPLOMA IN INFORMATION TECHNOLOGY Semester: 4 Subject Name VISUAL BASIC Sr.No Course content 1. 1. Introduction to Visual Basic 1.1. Programming Languages 1.1.1. Procedural,

More information

SPARK. User Manual Ver ITLAQ Technologies

SPARK. User Manual Ver ITLAQ Technologies SPARK Forms Builder for Office 365 User Manual Ver. 3.5.50.102 0 ITLAQ Technologies www.itlaq.com Table of Contents 1 The Form Designer Workspace... 3 1.1 Form Toolbox... 3 1.1.1 Hiding/ Unhiding/ Minimizing

More information

Budget Exercise for Intermediate Excel

Budget Exercise for Intermediate Excel Budget Exercise for Intermediate Excel Follow the directions below to create a 12 month budget exercise. Read through each individual direction before performing it, like you are following recipe instructions.

More information

Las Vegas, Nevada, December 3 6, Kevin Vandecar. Speaker Name:

Las Vegas, Nevada, December 3 6, Kevin Vandecar. Speaker Name: Las Vegas, Nevada, December 3 6, 2002 Speaker Name: Kevin Vandecar Course Title: Introduction to Visual Basic Course ID: CP11-3 Session Overview: Introduction to Visual Basic programming is a beginning

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals Agenda & Reading COMPSCI 80 S Applications Programming Programming Fundamentals Data s Agenda: Data s Value s Reference s Constants Literals Enumerations Conversions Implicitly Explicitly Boxing and unboxing

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Programming Language 2 (PL2)

Programming Language 2 (PL2) Programming Language 2 (PL2) 337.1.1 - Explain rules for constructing various variable types of language 337.1.2 Identify the use of arithmetical and logical operators 337.1.3 Explain the rules of language

More information

The Mathcad Workspace 7

The Mathcad Workspace 7 For information on system requirements and how to install Mathcad on your computer, refer to Chapter 1, Welcome to Mathcad. When you start Mathcad, you ll see a window like that shown in Figure 2-1. By

More information

Click on the empty form and apply the following options to the properties Windows.

Click on the empty form and apply the following options to the properties Windows. Start New Project In Visual Studio Choose C# Windows Form Application Name it SpaceInvaders and Click OK. Click on the empty form and apply the following options to the properties Windows. This is the

More information

EXCEL BASICS: MICROSOFT OFFICE 2010

EXCEL BASICS: MICROSOFT OFFICE 2010 EXCEL BASICS: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Microsoft Excel XP. Intermediate

Microsoft Excel XP. Intermediate Microsoft Excel XP Intermediate Jonathan Thomas March 2006 Contents Lesson 1: Headers and Footers...1 Lesson 2: Inserting, Viewing and Deleting Cell Comments...2 Options...2 Lesson 3: Printing Comments...3

More information

Managing Content with AutoCAD DesignCenter

Managing Content with AutoCAD DesignCenter Managing Content with AutoCAD DesignCenter In This Chapter 14 This chapter introduces AutoCAD DesignCenter. You can now locate and organize drawing data and insert blocks, layers, external references,

More information

CHAPTER 1 COPYRIGHTED MATERIAL. Getting to Know AutoCAD. Opening a new drawing. Getting familiar with the AutoCAD and AutoCAD LT Graphics windows

CHAPTER 1 COPYRIGHTED MATERIAL. Getting to Know AutoCAD. Opening a new drawing. Getting familiar with the AutoCAD and AutoCAD LT Graphics windows CHAPTER 1 Getting to Know AutoCAD Opening a new drawing Getting familiar with the AutoCAD and AutoCAD LT Graphics windows Modifying the display Displaying and arranging toolbars COPYRIGHTED MATERIAL 2

More information

The first time you open Word

The first time you open Word Microsoft Word 2010 The first time you open Word When you open Word, you see two things, or main parts: The ribbon, which sits above the document, and includes a set of buttons and commands that you use

More information

Microsoft How to Series

Microsoft How to Series Microsoft How to Series Getting Started with EXCEL 2007 A B C D E F Tabs Introduction to the Excel 2007 Interface The Excel 2007 Interface is comprised of several elements, with four main parts: Office

More information

(conditional test) (action if true) It is common to place the above selection statement in an If block, as follows:

(conditional test) (action if true) It is common to place the above selection statement in an If block, as follows: Making Decisions O NE OF THE MOST IMPORTANT THINGS that computers can do is to make decisions based on a condition, and then take an action based on that decision. In this respect, computers react almost

More information

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types Managing Data Unit 4 Managing Data Introduction Lesson 4.1 Data types We come across many types of information and data in our daily life. For example, we need to handle data such as name, address, money,

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Lecture 1 Introduction Phil Smith

Lecture 1 Introduction Phil Smith 2014-2015 Lecture 1 Introduction Phil Smith Learning Outcomes LO1 Understand the principles of object oriented programming LO2 Be able to design object oriented programming solutions LO3 Be able to implement

More information

Using Microsoft Excel

Using Microsoft Excel About Excel Using Microsoft Excel What is a Spreadsheet? Microsoft Excel is a program that s used for creating spreadsheets. So what is a spreadsheet? Before personal computers were common, spreadsheet

More information

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL BASICS: MICROSOFT OFFICE 2007 EXCEL BASICS: MICROSOFT OFFICE 2007 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Using Microsoft Excel

Using Microsoft Excel Using Microsoft Excel Excel contains numerous tools that are intended to meet a wide range of requirements. Some of the more specialised tools are useful to people in certain situations while others have

More information

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4. Introduction to Visual Basic and Visual C++ Arithmetic Expression Lesson 4 Calculation I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Arithmetic Expression Using Arithmetic Expression Calculations

More information

Computer Nashua Public Library Advanced Microsoft Word 2010

Computer Nashua Public Library Advanced Microsoft Word 2010 WordArt WordArt gives your letters special effects. You can change the formatting, direction, and texture of your text by adding Word Art. When you click the WordArt icon on the Insert tab, you will see

More information

Microsoft Excel Level 2

Microsoft Excel Level 2 Microsoft Excel Level 2 Table of Contents Chapter 1 Working with Excel Templates... 5 What is a Template?... 5 I. Opening a Template... 5 II. Using a Template... 5 III. Creating a Template... 6 Chapter

More information

Kenora Public Library. Computer Training. Introduction to Excel

Kenora Public Library. Computer Training. Introduction to Excel Kenora Public Library Computer Training Introduction to Excel Page 2 Introduction: Spreadsheet programs allow users to develop a number of documents that can be used to store data, perform calculations,

More information

PowerPoint 2016 Building a Presentation

PowerPoint 2016 Building a Presentation PowerPoint 2016 Building a Presentation What is PowerPoint? PowerPoint is presentation software that helps users quickly and efficiently create dynamic, professional-looking presentations through the use

More information

MAKING TABLES WITH WORD BASIC INSTRUCTIONS. Setting the Page Orientation. Inserting the Basic Table. Daily Schedule

MAKING TABLES WITH WORD BASIC INSTRUCTIONS. Setting the Page Orientation. Inserting the Basic Table. Daily Schedule MAKING TABLES WITH WORD BASIC INSTRUCTIONS Setting the Page Orientation Once in word, decide if you want your paper to print vertically (the normal way, called portrait) or horizontally (called landscape)

More information

Visual Studio.NET enables quick, drag-and-drop construction of form-based applications

Visual Studio.NET enables quick, drag-and-drop construction of form-based applications Visual Studio.NET enables quick, drag-and-drop construction of form-based applications Event-driven, code-behind programming Visual Studio.NET WinForms Controls Part 1 Event-driven, code-behind programming

More information

EPSON RC+ 7.0 Option. GUI Builder 7.0 EM145A2719F. Rev. 2

EPSON RC+ 7.0 Option. GUI Builder 7.0 EM145A2719F. Rev. 2 EPSON RC+ 7.0 Option GUI Builder 7.0 Rev. 2 EM145A2719F EPSON RC+ 7.0 Option GUI Builder 7.0 Rev.2 EPSON RC+ 7.0 Option GUI Builder 7.0 Rev.2 Copyright 2012-2014 SEIKO EPSON CORPORATION. All rights reserved.

More information