0% found this document useful (0 votes)
41 views

VB 1st Unit

Visual Basic 1st Unit for 3rd BCA

Uploaded by

aakil.ahmed131
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
41 views

VB 1st Unit

Visual Basic 1st Unit for 3rd BCA

Uploaded by

aakil.ahmed131
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 44
Visual Basic 6.0 Programmin ronment. Later on, Microsoft Visual Basic for Windows. Windows 95 / Windows 85 a serious development language for tion created the enhanced version of B. i SIC calle Visual Basic 6.0 for Windows requires at least. M 486 processor and a minimum of 16 MB of RAM.-A complet in Version of Visual Basic 6.0, the enterprise edition , requires more the space, 1.2 VISUAL BASIC 6.0 PROGRAMMING ENVIRONMENT Vistial Basic is initiated by using the Programs Option > Microsoft Visual ic Visual Basic 6.0. By clicking the Visual Basic 6.0 icon, we can view a copyright enlisting details of the license holder of the copy of Visual Basic 6.0 . Then it opens: Screen as shown in Fig 1 .1 with interface elements such as Menubar Toolbar and the! Project dialog box. These elements permit the user to build different types of Visual applications. ST Boe Fast ortun sun Query Dayan Too Adina, Wid KOU Activex Control % & \BWeard —OataProjet 5 ppkaton ‘Manager srs fie pees Document Ot Document Exe _appleston | Getting Started with Visual Basic 6.0 rhe Visual Basic IDE is made up of a number of components Menu bar. + Toolbar + Project Explorer + Properties Window + Form Layout Window + Toolbox ¢ + Form Designer + Object Browser. In previous versions of Visual Basie, se was designed as a (SDD. In a Single Document ach window is a free-float i that is con- tained within a main window and can ae as Visual Basic is the current application, But in Visual Basic 6.0, the i] face (MDI) format, In this format, the windows associated project will stay within a Swill stay within the single container known as th main container form. The following found in the IDE. Menu Bar — Menu bar displays the commands that are rec items have sub menu items that can be provide quick access to the commonly used once to carry out the action re| equivalent are given in Table 1.1. = Explorer a design mode 1B Used for debugging execution of a pro, While running a Stops execution of an pplication and returns to the design mode op Toggles breakpoint on Togg! menu Displays the value of Quick Watch command on the D the current selection in the code window Project Explorer mand on the View Start Run menu Break com nd on the Run menu gran End command on the Run menu le Breakpoint on the Debug n Traces through each line of code and into procedures Executes one code Procedure or statement, ata time in the Code window, TEL Displays the Meny Editor (Ea Dataview window steps component Visual Basic 6.0 Programming _ * The DriveListBox displays the valid disk drives and al them. * The FileListBox displays a set of files from which a user can select the desired one, * Line control draws a straight line to the Form. * Data control enables the us lows the user to select one of ‘er to connect to an existing database and display information from it. Form serves as a window that can be customized and controls, graphics and pictures: also be added to it. Project Explorer Docked on the right side of the screen, just under the toolbar, is the Project Explorer Mindow. The Project Explorer as shown in the Fig-13 serves ae a quick referener e Natious elements of a project namely form, classes and modules, All of the objects that make up the application are packed in a Which is a window that is designed as ny number of forms in a program, a Misual_Basic 6.0 Programming A property is a named attribute of a programming object. Properties define the Istie ofan object such as size, colour, ete. or sometimes the way in which it Bel example, a TextBox accepts properties such as Enabled, Font, Multi Line, Tex Width, etc. These are discussed below: 7 ® Enabled property allows the TextBox to be enabled or disabled at run time dep on the condition set to True or False. 7 * Font propert) ts a particular font in the TextBox. Multi Line property allows the TextBox to accept and display multiple lines time. © Text property of the TextBox control sets a particular text in the control, Visible property is used to hide the object at run time. Width property sets the TextBox to the desired width at design time. The properties that are discussed above are di design time by selecting the Properties window. Sign time. For example, the Current the design time. [Current X, Curren © A method is an action that can be For example, a cat is ano Properties might include long white hair, blue-eyes, three pounds weight; gb definition of cat must-not only encompass on its looks, but should alo imelude a eam Hemization ofits activities. Therefore, a cat's methods might be move, jump, play ete. i, sign time properties that can be set a But certain properties cannot be X and Current Y properties of a Form eannot beg it Y properties are ag in detail in Chap performed on objects. Tequires an object to provide them with a conte ing in Visual Basic, but the following stateme: Text1.Move 700, 400 nt, performs a very precise action, The TextBox control has other associated methods * The Refresh method enforces a Text1.Refresh refreshes the Te: * The SetFocus method moves the focus to the control. For exam the focus to TextBox control Text, 2 such as Refresh, Set complete repaint of the control ora Fy xt Box. Event Driven Programming Visual Basie programs are built around events, Events are a program. This will become clearer whe studied in contr lural languages, a written application ie through the program statements, one aft t arred to some other point in, nents are executed on Change,.Click, MouseMo in the code window for the ~“e The code the TextBox. ; « The Click event fires when t » The MouseMove event fires ‘As explained above, several eve of the events being common to mi e— State True or False Go border i ddition, the No border is shown. Ina i button, Maximize button, the title bar buttons are hidden from view. Je-pixe] width border is shown Fixed Single A sing] fe ‘This is the default setting. ‘The bo rd ler aro = foe ‘window is left so that it can be resized by the ‘A double-pixel width border is shown a form. Fixed ToolWindow This type of border is used for toolbars floating in the workspace. Only the title b box are visible, but in a reduced size. Sizeable ToolWindow Same as Fixed ToolWindow, but borders a Fixed Double Caption The title for the window is stored in the Caption property. The caption appears ° form's icon when the form is minimized. ‘ Control Box . This property determines whether the Control box, available by clicking the up ner/icon of a window, will be shown or not. Icon This property specifies the icon for the window in the upper left corner of th MousePointer This property sets the value that indicates ; 's the type of mouse pointer ¢ mouse pointer appears over a particular area of the object at Tana MaxButton i This property indicates whether 3 the Maximize button should be choice made available in the Control Box menu. MDIChild property specifies if this window must be h Moveable ‘This is a property introduced in V prevent the user from moving the other informational dialog boxes StartUpPosition ‘This is a property introduce window, you can pick a s are given in Table 1.3: Misual_Basic 6.0 Programming Using the Hide Method pe ide method hides a Form, For example, the following code hides the Form frmCaleulator. frmCalculator.Hide Using the Unioad Statement The Unload statement Temoves the form from the following code should be entered to unload frmCi Unload frmcalculator Using the Unioad Event The Unload event procedure is used to verify that the form shor "Specific actions that have to take ple when. display and releases its mem@ aleulator from memory. uld be unloaded or ‘¢ when the form is unloaded, The Unload event « ® The Form is unloaded using the ® The Form is closed by the user ¢ Menu or clicking the Close button Unload statement. ither clicking non the Setting Run Time and Design Time Propertie: “Many properties can be set at eith the Close command on the appl application title bar. Select the control or object whos Activate the Properties window. * Scroll to the property you w: * Enter a new setting. At runtime, pro writing a special ki of a selected object, Object.propertyName The left side of this assignment statement, Objec identifying the object and the Property that is to be Teset, statement gives the new Setting. When a program ting ee a ea asia’ at design ees De durin 5 a i a value Getting Started with Visual Basic 6.0 43° Forml.Caption = “Sample Application" Forml.WindowState = vbNormal Forml.Width = 5000 Forml.Height = 5000 d Sub Ss ——— II. Points to Ponder OO Fill in the blanks 1. The ______ event occurs when the form is closed by the user. 2. The _ method is used to display a form object. 3. A_____is a window that contains the application code and has other objects placed on it to create the user interface. “Oo 1.4 DEVELOPING AN APPLICATION ‘An application can begreated with the proje Ca project is a collection of files that are used to build an application) Writing a vag pa eyes involves the following two steps. * Visual cual programming st step dere + Code programming Step _ Co Visual programming step involves designing an application with various tools that come he Visual Basic package. Code programming ste involves writing programs ior. This section involves writing the first Visual Basic program. Before writ- specications balay have to be ‘ed, ‘The program window resembles Fig.1.5 comprising three CommandButton that perform specific actions represented by their captions and an ei gn ae specified Eee and Clear button clears e Exit button ter the app. pplication. CASESTUDY SM & Co. is a famous supermarket which s that include groceries, electronic appliances, station sof the supermarket are going in for computerizing the following requisites need to be considered ; j ® To select the mode of payment and category list from the set of available choig ® To update the category list as and when the new stock arrives. © To maintain a database of regular customers and update it. ® To enlist the availability of the items. © To give a list of choices for the products having different sizes. * To choose the mode of payment To display messages on entry and exit of the customers. To record the date and the day of transaction. ‘To choose the day of delivery of goods to a customer. To maintain a record about the sales made on various categories over a year, To access details of the transactions and all activities of the supermarket. How Visual Basic can be used to attain these requisites has been elucidated using ples throughout the book. Example 1.2 Let us consider a simple displ example. A New Standard EXE Proj Project dialog box. The stan: sponds by displaying the Pr commodities belonging to different ery, readymade garments, ete, their operations. During this lay program using the TextBox control i ject item is selected from the File menu that disp dard EXE is chosen for normal applications, Visual Bas ject and Form windows as shown in Fig. 1 ‘Though no changes have been made to the Form, ject is say 3 Getting Started with Visual Basic 6.0 Display.frm is given and the Save button has to be eli Sa’ bu licked on, Visual Basic then dips a Project As dialog box, which is similar to the Save File As dialo; le is saved as Display vbp.. object in roe Changing properties and Adding Controls Visual Basic 6.0 Programming 4 Changing the Properties of Form click anywhere i Bipides fo change the property of the Hye ean change the or ion et ea Beeerti Betdow oo Peers Table 1.4. The CommandButton contre can then be dragge iin the Toolbox, which places it in the centre of the Form. 1 fai) 0 sao roped atthe required location. It has a caption Command”, How UG RATE A Bie Properties window according to the specificalinn® € 1 ties alphabetically ai lowed for the other controls. Property window displays the p ategorized form with a description pane at the bottom ‘Adding Code for the Program 4 ; The visual programming step is now completed and selecting Save P1 ject command the File menu saves the work..The next step is the code programming step. Visua is written in the Code window that consists of an Object box and Procedure ‘Object box displays the name of the selected object associated with the Form. The e list box lists the procedures for an object such as click, double-click, ete. An event pro is written in the Code window that combines the control’s name, which is listed ListBox, an underscore and the event name. The Code window is viewed by sele m the Project window or by selecting Code from the View menu or represents a Code window. ‘Code editor window includes List Pro available for controls. Procedure Vi following code is entered for the Cli on it and press FA on pre. perties/Methods which presents a list of pr iew and Full Module View buttons are ava ick events of the respective controls in the een or Private Sub cuddisplay click( txtdisplay.Text = "visu. End Sub ) ual besic-q for windows) gael Private Sub cmdexit cig End maa a Getting Started with Visual Basic 6.0 txtOisplay.Text = " Visual Basic-6 for Windows 95" End Sub Private Sub CmdClear_Click() txtDisplay.Text = " ™ End Sub The appli When the ation is run-by clicking Start command from the nu or play button is clicked the Basic 6 for Windows 95 is dis- played in the TextBox. Clicking the Clear button awhile le clicking the Exit button terminates the application, Creating an Executable File Ending an Application ‘The End statement is used to terminate the execution of the application. It unloads all the ST IRL forms from memory. _ ee State True or False el ut A ue ‘a more eae a: listbox. “UWS «an create an executable file in Visual Basic Wy choosing Maka EXE File command from, ile menu. A Make EXE dialog box a . Now the file is saved as Display.exe in the "rely or Bans an the OK butln is kd. AS the aplication is eonverted into an executable file the user can run it on any other Windows program. duplication of Code, a separate module containing a procedure is created that implements the common code. This is a Standard module (Class modules (.CLS filename extension) are the foundation of object oriented program- ling in Visual Basic. New objects can be created by writing code in class modules, Bach module can contain larations May include constant, type, variable and DLL procedure declarations, Procedures eoeedu Asub function or property procedure that cont: unit. Data Types By default Visual Basic variables are of the varj e. The variant data type can store numeric, date/time or string data, When a'variable is declared, a data type is suy plied Vis for it that determines the kind of data it can s ‘The fundamental data types in Basic including variant are integer, long, single, double, string, currency, byte and boolean Visual Basic supports a vast array of data types, Each data type has Knits tte Kind of information and the minimum and maximum values it can hold. In addition, some ‘types can interchange with sofié other types. A list of ‘Visual Basic’s simple data types are _ given in Table 1.5. n ins pieces of code that can be executed as a loca of code Getting Started with Visual Basic 6.0 ‘There are many ways of declaring variables i jc. Depending on where the sariables are declared and how they are declared, we can determine how they can be used by our application. The different ways of declaring variables in Visual Basic are listed below and elucidated in this section. + Explicit Declaration while do on the Prossen, + Using Option Explicit statement dable assign Pandrake + Scope of Variables tinplict = ogee io dshoalt Explicit Declaration mean ys ign BHoe > F ass Declaring a variable tells Visual Basic to re ise memory, Itis not a must that variable should be declared before using it, Automatically whenever Visual Basic encounters anew variable, it assigns the default variable type and value. ‘This is called implicit declara-_ user, to have more control over the tion.Though this type of declaration is easier for the user, variables, it is advisable to declare them explicitly. The variables are declared with a_Di statement to name the variable and i "As type clausein the Dim statement allows wo define the data type or object type of the vari is called explicit declaration. —— yen ye Syn Larick > vasnable assign Dim variable [As type] ‘ 5 —— enaryt For example, f Jroqxam gtact 7 Dim strname As String Dim intCounter As Integer * Using Option Explicit | Statement nit to de Visual_Basic 6.0 Programming * Click Options item in the Tools menu. * Click the Editor tab in the Options dialog box. * Check Require Variable declaration option and then click the OK button Scope of Variables A variable is scoped to a procedure-level (local) or module-level vartable depending on h is decla ie Scope of a variable, procedure or object determines whic “ur application are aware of the va ration section of a Form and hen: . Loca recognized only in the procedure in wl lared. 5 and Static keywords. i = same module or to a © or to all the procedures in an application, a variable is declared with bro scope. Local Variables A local variable is one that is declared inside a procedure. This variable is onl; the code inside the procedure and can be declared using the Dim statement as gi Dim intTemp As Integer The local variables exist as lo Once a procedure is executed, ti by these variables is freed and Dim exist only as long as the pri Static Variables Static variables are not re-initialized each time Visual Basic invokes a pro retains or preserves value even when a procedure ends, In case we need to_ number of times a CommandButton in an application is clicked, a static cow to be declared. These static variables are also ideal for making controls a i le. A static variable is declared as given below. Static intPermanent As Integer heat hang ‘Variables have a lifetime in addition to scope. The values in la ables are preserved for the lifetime of an application Dim exist only while the procedure in which they value of a local variable can be preserved usit ng as the procedure in which they are declared, is ‘he values of its local variables are lost and the m can be reclaimed. Variabl ‘ocedure is being executed, A module-level v 122 Visual Basic 6.0 Programming 1.6 PROCEDURES AND CONTROL STRUCTURES Visual Basic offers different types of procedures to execute small sections of coding in appli. cations. The various procedures are elucidated in detail in this section. ‘This section also explain the various control structures available in the Visual Basic programming environ« ment. Procedures Visual Basic programs can he broken into smaller logical components siled_ procedure, Procedures are useful for condensing repeated operations such as the frequently used & lations, text and control manipulation, etc. Following are the benefits of using procedures ix programming. * It is easier to debug a program with procedures, which breaks a program into d logical limits. PR * Procedures used in one program can act as building blocks for other programs slight modifications. A Procedure can be a Sub, Functio Sub Procedures A spbnrocedure gan be placed in standard, class and form modules. Bach time the: is called, the statements between Sub and End Sub are executed. The syntax for dure is as follows. ~"TPrivate | Public] [Static] Sub procedurename[(arglist)] [statements] End Sub - arglist is a list of argument names separated by commas, Each argume in the procedure. There are two types of Sub Procedures—; ed =* a Event Procedures An event procedure is a proced _.), and the event name. The fo Form_Load event. — ane Private Sub Form Load( ) «Statement block. Getting Started with Visual Basic 6.0 + The Code window is opened for the module to which the procedure is to be added, + The Add Procedure option is chosen from the Tools menu, Procedure dialog box as shown in the Fig, 1.9, ‘The name of the procedure is typed in the Name textbox. Under Type, Sub is selected to create a Sub Procedure, procedure or Property to create a Property procedure, Under Scope, Public is selected to create a module or Private to create a procedure module. which opens an Add » Function to create a Function Procedure that can be invoked outside the © that can be invoked only from within the G Fig. 1.9 - typing Sub ProcedureName, nee eae Beene te ele caur A Nadie cedure returns a value and a Sub procedure does not return a value, : at they return value othe calling procedure ee as con WG binhanie-ren A § Visual Basic 6.0 Programming a ; ies JIt is ‘Aproperty procedure is used to create and manipulate custom pron al read anly properties for Forms, Standard modules and Clas! ttt value ofa three kinds-vf property procedures -Rroperty Let -t propeety aaa Property. rocedure that returns the val roperty an‘ PS = sets the réferencé to an object. Property Procedures Control Structures a Control statements are used to control the flow of program's execution. Visual ports control structures such as If... They Af.» Then tures such as Do While...Loop, Do...Loop while and For...Next method. If..Then...Else Statement ‘The If.. Then block is used for conditional execution of one or more statements, — If Condition Then Z statements a End If i ‘The statement is executed only if the condition is true. The condition is son, but it can be any expression that evaluates a numeric value. If Then used to define several blocks of statements, in order to execute one blo of statement illustrates If. Else...End If statements. If A=1 Then Statements Else Statements End If ‘The following example illustrates the If...Then...Else Example 1.4 Illustrate an example to check for display a message indicating the number it . dE ct is 0 Sea else MsgBox "The End If End Sub select... Case Statement ‘ select...Case structure is at block of statement ient to use than the Tf... Visual Basic 6.0 Programming Do... Loop Until Statement The Do.. Loop Until structure executes the statements until the ae is an infinite loop if the test fails and to get released from this infinite loop CTRL+ BREAK combination or End from the Run menu. The following code 1 Fotm_Load() procedure illustrates the structure. Example 1.5 Private Sub Form_Load() Do X$ = Inputbox$ ("Password Please 2") Loop Until X$ = "Vanilla Orange" End Sub The above example checks for the it asks for the password and until it is Onee the correct p: Password set to open the Format runtim is entered as “Vanilla Orange” the I assword is typed in the input box and clicked OK, the F _7 The For..Next Loop Statement jhe For...Next Loop is another way to make loops in Visual Basic. The follo from 1 to 50. For I= 1 to 50 step 1 Textl.Text = Str(1) Next. In order to count from 1 to 50 in stey For I= 1 to 50 step 2 Textl.Text = Str (1 ) Next ‘The loop counts as 1, 3, 5. ete.. Exit For and Exit Do Statement A For...Next loop can be terminated by an Exit ten ment block. a Gaal ps of 2, For 1 = 1 to 100 ( Textl.Text = str (1) i If I = 50 Then ‘ sjects or methods are called, a lot of coding is included that acts ier to read the code by implementing the With-End With state- be set and multiple methods can be called by using the With - ode is executed more quickly and efficiently as the object is evalu- ept can be clearly ‘understood with the following example. 7 6 c = True = "Welcome to Visual Basic 6.0" ding, the object textprice, which (the Name property of TextBox has been rice) is evaluated only once instead of every associated property or method. simpler and efficient. ‘andl aa __ procedure is used to creat Visual Basic 6.0 Programming defined t; ypes and object variables. The individual elements of an array are all of th di ata type. Following are the two types of arrays in Visual Basic © Fixed-size array The size of array always remains the same ® Dynamic array The size of can be changed at run-time In the following section let us discuss about the ways of declaring different types of Fixed Size Arrays Fixed arrays can be declared by giving a name Parentheses. The upper limit should always be will fixed arrays in different'cases are given below Array declaration in the General Declarations section of a module or a proc shown in this example, Dim Tengths(9) As Integer In the above illustration, lengths is the name of the Parentheses is the upper lim; elements, with index number to the array with the upper li hin the range of Long data array and the number 9 i it of the array. The above declaration creates an ai rs running from 0 to 9. 7 Dim lengths( 1 To 10) As Int In the above statement, an array of 10 elements is declared but with indey 1 to 10, A public array can be created using Public digits(20) As Integer eger Visual Basic 6.0 Programming If the same is implemented as an array, then the statement changes to the Text1.text = Electronicgoods(i).prodname Here i is the index number of the array. User-defined types can also be passed to procedures to allow many related i argument. Sub ProdData( Electronicgoods As ProductDetails) Text1.Text = Electronicgoods.Prodname Text2.Text = Electronicgoods.Price End Sub Constants Constants are named storage locations in memory,the value of which does ‘ing program execution, They remain the same throughout the program exe user wants to use a value that never changes, a constant can be declared Const statement is used to create a constant. Constants can be declared in loc ule or global scope and can be public or private as for variables. Constants. illustrated below. , Public Const gravityconstant As Single = 9.81 Predefined Visual Basic Constants i ‘The predefined constants can be used anywhere in the code in place o values. This makes the code easier to be read or write. ia example consider a statement that will set the window state of Forml.Windowstate = 2 * _ __ The same task ean be performed using a Visual Basic constant, statement. visual Basi Many built functions ar categories that Date and Time Date and time a of the number ‘To display both # given below. — MsgBox Here ‘& ii tion, DateAdd () Returns a date to which a specific added. DateDiff () Returns a Long data type value sp between the two values. Returns an Integer containing the given date, verts a string to a date. Converts a string to a date Returns a date for a specified year, n DatePart ( ) DateValue ( ) ‘TimeValue () DateSerial ( ) DateDiff Function The DateDiff function returns the intervals between two dates in terms 0 days. The syntax for this is given below. DateDiff(interval, datel, date2[, firstdayofweek[, firstweekofy Format Function The format function accepts a numeric v, fied by the format argument. The synt: Format (expression[, alue and converts it to a string ‘ax for this is given below. Logical Operators ‘There are six logical ¢ And Xor, Eqy and Working with ‘ols jhis chapter introduces us to the various controls available in Visual Basic and the vari- ous ways of creating and using them in an application. © Creating and Using Controls © Working with Control Arrays INTRODUCTION 68 Visual Basic 6.0 Programming Most of the controls provide choices to users that can be in the fon oot oa tion CheckBox controls, ListBox entries or ScrollBars to select a value. Let us discuss trols by means of a few simple applications in this chapter. Classification of Controls Visual Basic controls are broadly classified ag reandery a Anise ae a able objects. Standard controls such as CommandButton, Label and Frame con “amen male “ERE Tis aia ‘always included in the Toolbox which cannot be ActiveX controls exist as separate files with either .VBX or .OCX extension. specialized controls such as * MSChart Control + The Communications control * The Animation control * The ListView control ‘* An ImageList control * The Multimedia control + The Internet Transfer control + A WinSock control * The TreeView control * The SysInfo Control + The Picture Clip control Z These built-in ActiveX controls will be discussed at length in Chapter 14. Some’ objects support OLE automation, which allow programming another applicatio within Visual Basic application, Tabindex Property of Controls "Visual Basic uses the Tabindex property to determine the control that w us next when a Tab key is pressed, Every time a Tab key is pressed, value of TabIndex for the control that currently has focus and then it trols searching for the next highest TabIndex number. Working with Controls dex of other controls to reflect insertions and deletions. We can make changes at the TabInt using the Properties window or at run time in code. design time Using Text Box Control ‘A TextBox control, sometimes. called an. edit. field or edit control, displays information en- design time. This could be entered by the user or ‘assigned to the control in code at tered a run time. Setting Properties to a Text Box |. Text can be entered into the text box by assigning the necessary string to the text property of the control Irthe user is interested in displaying multiple lines of text in a TextBox control, he has to set the MultiLine property to True. If a multiple-line TextBox does not have # fh izontal ScrollBar, text wraps automatically even when the TextBox is resized. Ih order to customize the seroll bar combination on a TextBox, set the ScrollBars property. ScrollBars will always appear on the TextBox when its MultiLine property is set to pt None (0). ‘True and its ScrollBars property is set to anything exce « Ifthe user sets MultiLine property to True, he can use the Alignment property to set the alignment of text within the TextBox. ‘The text is left-justified by default. If the MultiLine property is False, setting the Alignment property has no effect. ‘A TextBox control can also act as a destination link in a DDE conversation. 1 In order to work with the part of a text in a TextBox, the text can be selected using the following three properties. + SelLength Returns or sets the number of characters selected. 1 selStart Returns or sets the starting point of selected text. When no text is selected, SelStart indicates the position of the insertion point. i SelText Returns or sets the string containing the currently selected text. If no text selected, SelText consists of a zero-length string. “i ue « The selected text can be copied to the Clipboard by using SelText in the: Clipboard.SelText text, [format] In the above syntax, text is the text that ha: has three possible values. : * VbCFLink - cor cc Visual Basic 6.0 Programming Using a Label Control A Label control is a graphical control you can use to display text directly. Properties of a Label control + We can write code that changes the caption property displayed response to events at run time. We can also use a Label to identify a ‘TextBox control, that doe: sn’t have its own Caption property. * The AutoSize and WordWr ‘ap properties should be set if the user Properly display variable-length lines or varying numbers of lines * A Label control can also act as a destination in a DDEconversat Property to establish a link, set the Linkltem property to s conversation, and set the LinkMode property to activate Properties have been set, Visual Basic attempts to initiate t displays a message if it’s unable to do so. a * Set the UseMnemonic property to True if you want to define a property of the Label as an access key Using a Command button Late _ A Command Button control is used to begin interrupt or end ‘CommandButton appears pushed in and so is sometimes calle: Properties of a Command Button Control * To display text on a CommandButton control, set * An event can be activated by clicking a A button’s background colour can be set desired choice. e text colour of a command button he Font of a command button ox to the desi Loe a Using OptionButton Control OpvonButton provides a set of choices from which a user can select only one button by g it at run time, ng the value property to True in code like Option1.Value#True + Using the shortcut keys specified in the Caption of a Label n OptionButton at run time, its Enabled property is set to False. Let us de- r system application that illustrates the operation of the OptionButton con- n contains a Label, TextBox, CommandButton and three OptionBatton con- Example + A new Standard EXE project is opened and the Form and the project is saved as and Option.vbp respectively. + The Form is designed as per the following specifications table (Table 2.1). The designed appears as in Fig. 2.1 Table 2.1 Visual Basic 6.0 Programming lication responds to the follow er ertotchange event ofthe TextBox read variable as currentval. * The click event of optOct button returns cul © The click event of the optHex button return re © The click event of the optDec button returns the decim: currentval. ‘The following code is entered in the general d Dim currentval as variant ‘The variable is initialised to 0 by defau the number system (Octal, Hexadecimal) Private Sub Text1_Change() If optOct.Value = True Then currentval = Val("80" & LTrim(Texti.Text) & 8") Elseif optDec.value = True then currentval = Val(Ltrim(textl.text) & "&") Else currentval = Val("8H" & LTrim(Text1.Text) & "&") End If End Sub ‘The Val function is used to translate string to a number and can 1 decimal strings. The LTrim function trims the leading blanks in is entered in the click event of the OptionButton controls. Private Sub opt0ct_Click() Textl.Text = Oct(currentval) End Sub x Private Sub optHex Click() i Text1.Text = Hex(currentval) End Sub Private Sub optDec Click() fede = Format(currentval) ‘The following code is entered i i Private Sub cmcloos Cis ee at Unload Me It. The change event that is in effect and Press ane Additem method ices the following syntax: asect -Addrvem item, Index onject -Removeltem index ‘The following code verifies an item private Sub cmdRemoveLi stl! if MyList.ListIndex >-1 myList .removeltem MyList End if Ené Sub ‘An error occurs if you attempt to u Selecting an Item from a List Box To access items in a list box, we use # ‘erty sets the index number of the umber 0.The ListIndex returns -1 if. one more than the index number of the the index of the last item added to the ‘The following example adds an item .Additem “Television* istindex = List].New! 7A visual Basic 6.0 programming | Viua Base 60 Pt tr = MyList M st Index) yrist List! di = nywist.List ( : ‘s ring for a Co! nboBox, the Text prol ert; turn the s! yperty of the To ret a the following example str = ombListl. Text Sorting the List The Sorted propel to display the list items in r in alphanu to enable a list to appe@ i ‘in which they are added to the rty is set to True the orde’ 7 Using the ComboBox 2 i ‘A ComboBox combines the features of TextBox anda Lista Ta - by typing text into the ComboBox or by selecting styles that are represented in Fig. 2.2. to select eith are three types of ComboBox * Dropdown Combo (style 0) # Simple Combo (style 1) + Dropdown List (s1 The Simple combo box displays an edit area with an attached list box a ately below the edit area. A simple ComboBox displays the contents of ‘The user can select an item from the list or type an item in the edit box por hex, A ScrollBar is displayed beside the list if there are too many items to B jist box area my The Dropdown combo box first appears as onl the right. The list portion stays h down the list portion. The user edit area. The Drop. wn list combo box turns the the control looks like the drop- aoa the list. The difference bet area in the dropdown | type an item in the edit the list : area. This area, ho Form. The full list is An illustration of diff «is saved and the application is run by pre qe p79%h par, we can find the change in the speed the HS — F False Fate True om 2 . state 7 function translates a string toa character, _ List Box provides a set of choices to the user, _ vill in the blanks ee 1. The Value property of the scroll bar represents it rateger between ____ and io, ComboBox combines the feature of _ method removes list entries from a list same event procedures. Adding controls with control ing multiple controls of same type at design time, Creating Control Arrays at Designtime _ ‘There are three ways to create a control array. + Assigning the same name in the Name p: + Copying an existing control and then Paste option from Edit menu. * Setting the Index property to a va Table 2.4 (Contd) Command Button Command Button Text box Command Button In addition to these controls, six command bi named as emdPlus, emdMinus, cemdDiv, ¢ with their captions set as +, -, / 28 lm The following variables are declared in the Public curval As Double Public prevval As Double Public choice As String Public result As Double * The following code is entered in the emd_Click() ( Private Sub cmd_Click(Index As Integer) curval = Val(Textl.Text) End Sub + In the emdAC_Click() procedure, the fo Private Sub cmdAC_Click() curval = prevval = 0 Textl.Text = 7 End Sub * The following code is written in the emdN Private Sub cmdnegat ive Click() curval = ~cupyal Textl.Text = Str(curval) End Sub ; + The following code iV controls is entered in the c respectively, 7

You might also like