visual basic - ::ices::indian computer … notes.doc · web viewif the keyword step follows the...

241
NetScape COMPUTER ACADEMY 1 Chapter 1 INTRODUCTION Introduction In the Beginning VISUAL STUDIO was a loose collection of programming tools and utilities. VISUAL STUDIO 6.0 is now starting to show tighter integration between these tools and utilities. VISUAL STUDIO is a collection of Microsoft Visual Development applications and related tools. This collection is intended to provide a single framework for all the development needs of an enterprise development team. The tools are designed to complement each other while providing a complete design, development, and deployment environment. VISUAL STUDIO contains following tools VISUAL BASIC VISUAL C++ VISUAL J++ VISUAL INTERDEV VISUAL FoxPro The tools in VISUAL STUDIO are designed to address the varying development needs of different types of developers, including Web developers, Application developers, Enterprise developers, and content developers. A Web Developer is one who is developing and deploying applications over the Web. Such a person might use Microsoft Internet Information Server (IIS) and Microsoft SQL Server along with Active Server Pages (ASP) on the back end, and Web pages containing VBScript , ActiveX Controls , and Java Applets on the front end. An Application Developer is one who is developing and deploying standalone Windows applications and tools. They might use a combination of VISUAL BASIC and VISUAL C++ to develop such programs, using Microsoft Access or any other RDBMS as their database. An Enterprise Developer is one who is developing strategic business applications that help manage a company’s enterprise resources. Enterprise developers are interested in using teams of developers to build business components that are scalable and can be distributed around the enterprise. VISUAL BASIC was introduced to the public in 1991. It has improved with every release. With each release, the product has gotten both better and more popular. By 1998, VISUAL BASIC was the primary language used by more than half the developers in United States. This book is designed to be a completed desk reference to the many techniques and tools related to VISUAL BASIC . VISUAL BASIC is an ideal programming language for developing professional applications for Microsoft Windows . It makes use of Graphical User Interface (GUI) for creating powerful application. When programming in visual Basic Developer must decide how the application interacts with the user. The user may do any event in the application on various controls. Windows introduced the concept of a message. Every action you perform in Windows generated one or more message. For instance, if the user moves the mouse across the screen, a series of messages are generated for each position the mouse occupies while it is being moved. If the user moves the mouse over the window for an application that is running, windows send these messages to that application. The application then has to determine if the user is doing something within itself, or if the user is just “passing through.” Every application has to look as every message sent by Windows and make this determination. The code required to make this work is lengthy and complex, to say the least. Besides having to handle simple messages such as a mouse movement, a Windows application also has to handle complex actions, such as when the user moves a window from one place to another. Windows tells your program what the user is doing, but it doesn’t do any of the work of handling the user’s action for you. Your application has to repaint your windows in a new position, for instance. Even after you have dealt with all the windows messages you might receive, you’re still not done. Your program still has to have code to handle all of your applications features.

Upload: ngodung

Post on 29-May-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 1

Chapter 1

INTRODUCTIONIntroductionIn the Beginning VISUAL STUDIO was a loose col lect ion of programming tools and uti l i t ies. VISUAL STUDIO 6.0 is now start ing to show tighter integration between these tools and uti l i t ies. VISUAL STUDIO is a col lection of Microsoft Visual Development appl ications and related tools. This col lection is intended to provide a single framework for al l the development needs of an enterprise development team. The tools are designed to complement each other whi le providing a complete design, development, and deployment environment.VISUAL STUDIO contains fol lowing tools

VISUAL BASIC VISUAL C++ VISUAL J++ VISUAL INTERDEV VISUAL FoxPro

The tools in VISUAL STUDIO are designed to address the varying development needs of different types of developers, including Web developers, Appl icat ion developers, Enterprise developers, and content developers.

A Web Developer is one who is developing and deploying appl ications over the Web. Such a person might use Microsoft Internet Information Server (IIS) and Microsoft SQL Server along with Active Server Pages (ASP) on the back end, and Web pages containing VBScript , ActiveX Controls , and Java Applets on the front end.

An Application Developer is one who is developing and deploying standalone Windows appl ications and tools. They might use a combination of VISUAL BASIC and VISUAL C++ to develop such programs, using Microsoft Access or any other RDBMS as their database.

An Enterprise Developer is one who is developing strategic business appl ications that help manage a company’s enterprise resources. Enterprise developers are interested in using teams of developers to bui ld business components that are scalable and can be distr ibuted around the enterprise.

VISUAL BASIC was introduced to the publ ic in 1991. I t has improved with every release. With each release, the product has gotten both better and more popular. By 1998, VISUAL BASIC was the primary language used by more than half the developers in United States. This book is designed to be a completed desk reference to the many techniques and tools related to VISUAL BASIC .

VISUAL BASIC is an ideal programming language for developing professional appl ications for Microsoft Windows . I t makes use of Graphical User Interface (GUI) for creating powerful appl ication.

When programming in v isual Basic Developer must decide how the appl icat ion interacts with the user. The user may do any event in the appl ication on various controls.

Windows introduced the concept of a message. Every act ion you perform in Windows generated one or more message. For instance, i f the user moves the mouse across the screen, a series of messages are generated for each posit ion the mouse occupies whi le i t is being moved. I f the user moves the mouse over the window for an appl ication that is running, windows send these messages to that appl ication. The appl ication then has to determine i f the user is doing something within i tself , or i f the user is just “passing through.” Every appl ication has to look as every message sent by Windows and make this determination. The code required to make this work is lengthy and complex, to say the least . Besides having to handle simple messages such as a mouse movement, a Windows appl icat ion also has to handle complex actions, such as when the user moves a window from one place to another. Windows tel ls your program what the user is doing, but i t doesn’t do any of the work of handl ing the user’s action for you. Your appl ication has to repaint your windows in a new posit ion, for instance. Even after you have dealt with al l the windows messages you might receive, you’re st i l l not done. Your program sti l l has to have code to handle al l of your appl ications features.

VISUAL BASIC revolutionized al l this tedious code. Instead of a programmer’s having to write lengthy code to make a window respond to the mouse, VISUAL BASIC handles al l those actions and hides them from the programmer. To indicate to your program that the user c l icked the mouse, VISUAL BASIC provides an event instead of a series of messages. You then write code to respond to the event and not the message. With the introduction of event, VISUAL BASIC programmers could concentrate on writ ing appl ication’s features and not worry about the low-level things such as why a button c l ick worked. They could simply write the code to run when a button was c l icked. The code that runs when the user c l icks a button or any other event is known as an event handler.

VISUAL BASIC also provides a design environment in which the programmer could draw an appl ications window instead of writ ing code to create them. This abi l i ty to rapidly draw the interfaces of an appl icat ion made VISUAL BASIC into an excel lent tool for creating prototypes. A prototype is a prel iminary version of an appl ication used for

Page 2: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 2

discussion among designers. For consultants, a prototype is an excel lent way to show your cl ient what the appl icat ion might look l ike.

Coding in VISUAL BASIC is quite transit ion to tradit ional. Work of the user is guided through a l inear path of execution and is l imited operations. In a GUI environment, the number of options open to the user is much greater, al lowing more freedom to the user and developer. Features such as user fr iendl iness, faster appl ication development, ActiveX technology and Internet features make VISUAL BASIC an interesting tool .

VISUAL BASIC was developed from BASIC (Beginners All-Purpose Symbolic Instruction Code) programming language.

VISUAL BASIC 6.0 requires at least Windows NT/Windows 95/98, 486 Processor and a minimum of 16 MB RAM. A complete instal lat ion of VISUAL BASIC 6.0 (Enterprise Edit ion) requires more than 250 MB hard disk space.

Page 3: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 3

Chapter 2

Getting StartedEvent Driven Programming

Forms and controls are the basic elements in the user interface of any VISUAL BASIC appl ication. In VISUAL BASIC these elements are cal led as objects. Each object has their own properties and react to external events.

Starting Visual Basic

VISUAL BASIC is a component of Visual Studio .

Click Start Microsoft Visual Studio 6.0 Microsoft Visual Basic 6.0 or Double c l ick on the Vb6 icon i f i t is avai lable.

A New Project dialog box wi l l appear with fol lowing options.

New This tab enables us to create a New project. In this window, you’ l l see some of the project types that VISUAL BASIC supports. They are

Standard Windows EXE Programs ActiveX Exe files ActiveX DLLs ActiveX Controls Programs written by VISUAL BASIC Application Wizard Data Projects IIS(the Microsoft Internet Information Server) applications VISUAL BASIC add-ins ActiveX document DLLs ActiveX document EXE files DHTML applications VISUAL BASIC Enterprise Edition Controls

Existing This tab enables us to select already exist ing project

Recent This tab l ists the Visual Basic projects that are used recent ly.

Whenever a project is opened or a new project is started, Visual Basic 6.0 Integrated development Environment (IDE) appears.

Selecting standard Exe in the project dia log box creates a new project . This wi l l open a new project named project1.

Creating a Project in VISUAL BASIC

Page 4: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 4

There are three different edit ions of VISUAL BASIC:

The Learning Edition : - The most basic edit ion. This edit ion al lows you to write many different types of programs, but lacks a number of tools that the other edit ions have

The Professional Edition : - Designed for professionals. This edit ion contains al l that the Learning Edit ion contains and more, such as the capabi l i ty to write ActiveX controls and documents.

The Enterprise Edition : -Which is the most complete VISUAL BASIC edit ion. This edit ion is targeted towards professional programmers who may work in a team and includes addit ional tools such as Visual SourceSafe, a version-control system that coordinates team programming

IDE- Integrated Development environment.IDE is a commonly used term in the programming world to describe the interface and environment that we use to create our appl icat ion. I t is also referred as design environment. The IDE is made up of fol lowing components.

Menu Bar, Tool Bar, Toolbox, Project Explorer, Propert ies Window, Form Layout Window, Form Designer, Object Browser.

In VISUAL BASIC IDE is Multiple Document Interface (MDI) format. In this format, the windows associated with the project stay within a many container form.

Menu bar : - The menu bar displays the commands that are required to bui ld an appl ication.

Tool bar : - The tool bar provides quick access to the commonly used commands and a button in the toolbar is cl ick to carry out the action represented by it . Visual Basic has four default tool bars that can be made to appear on the screen or hidden using .

View Tool bars in menu section.

1. Standard I t contain al l prel iminary icons2. Edit Edit ing VISUAL BASIC code.3. Debug To assist in finding errors in the coding.4. Form Editors To adjusting items on the form.

Page 5: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 5

Chapter 3Toolbox, Form, Properties & Project

ExplorerThe Toolbox

Tool box contain number of controls that can placed on a form when a mouse cursor is placed on the control a pop up tool t ip wi l l appear displaying a short descript ion of the control . You use the toolbox to add controls to your projects, and you document so in a very easy way- just cl ick a tool , and draw the new button in the form. The toolbox is loaded with controls you can add to your forms-textboxes, labels, l ist boxes, image controls, checkbox controls etc. When you add a new ActiveX control to your project, that control appears in the toolbox, and you’re ready to add it to your form.

Tool Box Controls

Pointer : - Pointer is not real ly a component. I t provides a way to move and resizes other controls.

Label : - Labels lets you provide information to the user about the purpose of your form controls. Labels display a text that the user cannot modify or interact with. You can use this control to d isplay text that labels other parts of the form that don’t have their own captions. You can change the text in a label control at runtime or design t ime by sett ing Caption property. You can also format, word-wrap, or s ize a label to fit i ts text. You can size the label as desired using Top, Left, Width and Height properties. To format text in a label use its propert ies l ike Autosize, WordWrap, FontBold, FontItal ic , FontName, FontStr ikethru,FontUnderl ine etc. To al ign the text in label use the Al ignment property, which have the values 0-VbLeftJusti fy, 1-VbRightJusti fy, and 2-VbCenter. You can use label controls to give access keys to other controls l ike Textbox. For this type the Caption of a Label with an ampersand [&] in front of the character for which you want to use as access key, draw the control for which you want to set the focus. That is the control should have the next TabIndex property value. Labels do not accept focus, so when you press the access key, i t wi l l set the focus to the next control in TabIndex order. When you access keys, make sure to set the label’s UseMnemonic property to True.

Frame control : - The Frame control can be used to d ivide the controls into logical groups. They serve as a visual and functional container for other controls. For example you can draw different opt ion button groups in different frames. You can change the Appearance of a Frame using Appearance property. To set the size of a Frame use Top, Left, Width, and Height properties. To group controls, first draw the Frame control and draw the controls in i t . I f you draw a control outside the frame and then try to move it

Page 6: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 6

inside, the control wi l l be on top of the frame, not in i t , which means the control wi l l not be grouped with other controls in the frame.

Check Box : - The Checkbox control is used to provide the user a Yes or No choice for a particular question. It has three values 0 (Unchecked), 1 (Checked) and 2 (Grayed). You can use a checkbox’s Value property to determine its state. The most commonly used event for Check box is Cl ick event. You can set the caption of a checkbox control using

Caption property.

Textbox : - Text box is a control used to d isplay the messages and enter text. Textbox can be used in a variety of configurations, including a mult i l ine version that can hold unl imited amount of text. I t can also add its own scrol lbars i f the amount of text is larger than the vis ible s ize. Text in a Textbox can be edited. You can also lock the textbox to disable edit ing. To create Mult i l ine textbox, set i ts Mult i l ine property to True. You can set scrol lbars to a textbox and its values are 0-None, 1-Horizontal , 2-Vertical , and 3-Both. To change the al ignment of a Textbox, set Al ignment property as 0-Left, 1-Right, and 2-Center. To Make a Textbox Readonly, you can set Locked property to True. To Disable a Textbox, set i ts Enabled property to False. You can also format the Font, Fontsize etc. using Fontname, FontBold, Font Ital ic, FontSize etc. The SelLength property returns or sets the number of characters selected, SelStart property returns or sets the start ing point of selected text, and SelText property returns or sets the str ing containing the currently selected text. To convert a standard TextBox into Password box, you just assign some character usual ly[*] to the textbox’s PasswordChar property.

List Box : - The l ist box displays the l ist of i tems from which user can select. You can add items to the l ist box using AddItem method and also remove an item using RemoveItem method. To c lear al l the contents of l istbox use Clear method. There are variety of properties to count the no. of i tems, sort ing the l ist etc. To count the total no. of i tems in a l istbox use ListCount property, to Sort the Listed items set Sorted property True. The ListIndex property returns the Index value of currently selected item in the Listbox. I f none is selected ListIndex returns –1. You can use Listbox’s Cl ick, DblCl ick events to handle different operat ions. To Create Checkmarks in a Listbox set Listbox’s Style property to 1-Checkmark List Box.

Page 7: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 7

ComboBox : -The ComboBox is a very flexible control . It combines a drop-down List Box and a TextBox in one control . This al lows the user to select an item from the drop down l ist box. You can create three different styles of ComboBox.

i) Dropdown List : - This sty le of ComboBox al lows the user to pick from a l ist but not type into the text port ion of the control .

i i ) Simple Combo : - In this Style, the user can type a choice, but the l ist drop down under text box. This sty le is rarely used.

i i i ) Dropdown Combo : - This sty le provides both features: a drop-down l ist as wel l as a text portion where the users can type their choices.

Use the AddItem method to Add items, RemoveItem method to Remove Items from a Combo Box. You can use the events l ike Cl ick, DblCl ick, Change etc to perform different operations. The Sorted property is used to create sorted l ist. Use the Clear method to Clear the contents of Combo Box. You can also Lock the Combo Box using Locked property. List Count property returns the Number of I tems in Combo Box, ListIndex returns the Index of currently selected item.

Scroll Bar : - Horizontal Scrol l bar, Vertical Scrol l bar a l lows the user to select a value in the specified range. This type of control is intuit ive for the user because, as the user drags the control , another change on the form such as color or text also changes. To add horizontal or vert ical scrol lbar, just pick the control and draw it on your form. After you place the scrol lbar, you can change its Maximum and Minimum values using Max and Min properties. The Maximum value must be between 0 and 32767. There are three ways to change the sett ing of a scrol lbar, by moving the thumb, by c l ick ing the an arrow, and by cl icking on the area between the thumb and arrow button. You can set the LargeChange property to determine how much the scrol l bar value should change when user c l icks on the scrol lbar i tself , not the thumb or arrow. Set Smallchange property to determine the amount of value to be changed when the user cl icks on arrow button. To get a scrol lbar’s current value use Value property. When the user changes the sett ing in a scrol lbar, a change event occurs and you can react to those changes with an event handler attached to that event. The change event occurs after the action is completed. The Scrol l event updates as the act ion is happening. I t ’s very useful to be able to update the screen as the user scrol ls. To show or hide scrol lbars use Visible property.

Timer : - Timer control al lows you to react to elapsed or passing t ime whi le an appl ication is running. The t imer can be programmed to noti fy you after a number of mil l iseconds have elapsed. A mil l isecond is 1/1000 t h of a second. The maximum interval is just s l ight ly larger than a minute. Timer control executes the t imer events at specified intervals. This control is not vis ib le at run t ime. To enable or disable this control use Enabled property. The Interval property sets the interval between Timer events. This control only has the event handler Timer where you can write the code when the Timer event occurs.

DirListBox : - Dir l istbox al lows the user to select the directories and path. It g ives a l ist of directories in the current directory on the users computer. This control is commonly used to bui ld a custom file / d irectory dialog. This control works together with the DriveListBox and Fi leListBox controls. To add a DirListBox control just use its tool in the toolbox. The important property of this control is Path, which holds the path of current directory. When the user changes the current path, a Change event occurs. You can write code in this event handler. Eg: Sub Dir1_Change()

Fi le1.Path=Dir1.PathEnd Sub

Page 8: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 8

FileListBox : - The Fi leListBox displays a set of files from which user can select. It provides a l ist of files in a directory from which the user can select a file. Use this control along with DriveListBox and DirL istBox controls. To add this control , use its tool in the toolbox. The important properties of a Fi le l ist box are Path, F i lename, and Pattern. The path property returns the current path, F i lename returns currently selected filename, and Pattern determines the type of files to be displayed in the Fi leL ist box. You can have more than one type of file pattern seperated by semicolon. (Eg:- *.BMP; *.GIF; *. JPG; *.WMF). you can write codes in Cl ick event handler of a Fi lel ist box.

Sub Fi le1_Cl ick()MsgBox Fi le1.Fi lename

End Sub

DriveListBox : - The DriveListBox displays the val id disk drives, network drives and al lows the user to select one of them. Use this control along with DirListBox and Fi leListBox to create custom Fi le dialog boxes. You get the currently selected drive in a drive l ist box using its Drive property, and when the user changes the drive in that control , a Change event is generated. You can write code in this event handler as fol lows.

Sub Drive1_Change()Dir1.Path=Drive1.Drive

End Sub

Shape : - Shape control is able to create many shapes, including rectangles, c ircles and ovals. You draw a shape using the shape tool . To set the shape’s type, you set the control ’s Shape property to one of the fol lowing. 0-vbShapeRectangle, 1-VbShapeSquare, 2-VbShapeOval, 3-VbShapeCirc le, 4-VbShapeRoundedRectangle, 5-VbShapeRoundedSquare. You can also set the width of the shape’s drawing l ine with the BorderWidth property and fil l the shape using Fi l lColor and Fi l lStyle propert ies. The BorderStyle property lets you select the style of the shape’s drawing l ine, including using dots and dashes.

Image : - The Image control provides a much smaller set of features than PictureBox and uses less memory and other system resources and is a l ightweight control . The image control is able to display a variety of images formats including Bit Map Picture (BMP). Icon Fi les ( ICO), Windows Meta Fi le (WMF), Graphic Interchange Format (GIF) and Joint Photographic Experts Group ( JPEG) formats. To draw an image control , just use its tool from the toolbox. After adding image control , use Picture property to specify the picture filename to d isplay. By default, image controls shape themselves to the image you display, i f you want to stretch an image to fit the image control , set the image control ’s Stretch property to True. Use BorderStyle property specify border for image l ist control . You can load a p icture to this control at runt ime using LoadPicture() function.

Eg:Set image1=LoadPicture(“C:\WINDOWS\CLOUDS.GIF”)

Page 9: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 9

OLE Control : - OLE control al lows you to embed any object on your form that complies with Object Linking and Embedding protocols (OLE). As you add this control to your form, you get a l ist of avai lable OLE types you can use.

PictureBox : - The PictureBox display icons, bitmaps and metafiles. I t d isplays text or acts as a visual container for other controls l ike frame. When you have to do some advances programming that required the use of the Windows API , you must use this control instead of image l ist. I t ’s the only control that can appear by itself in an MDI (Mult iple Document Interface) form. As with image controls you can load images to this control at runt ime using LoadPicture() function. To add a picture box control just use that control from Toolbox. You can set AutoSize property to True to resize the picturebox to fit the picture. To set the picturebox’s picture at design t ime use Picture property. You can also draw other controls in a picture box and also draw shapes l ike l ine, circ le etc.

Command Button : - Command button carr ies out the specified action when the user chooses it . This control is used to let the user select a course of act ion. You can also display graphics on your command button by changing the style property to graphical and select the picture you want to display using picture property. This is a very common control in windows appl icat ions. You use button’s Capt ion property to specify the text to be displayed on Button. To change background color or display any picture as background set the style property to Graphical and specify the background color or background picture. The most commonly used event of a command button is Cl ick Event. To give a button access key just place an ampersand [&] in front of the character for which you want to use as access key. The default property is used make the command button default by which you can access the c l ick event handler of that button by pressing Enter key. The cancel property is used to access that button using Escape key.

Option Button : - Also known as radio buttons, this control a l lows the user to select one of a group of opt ions. To create separate group of options you must draw it in a container l ike Frame or P ictureBox control . When you add option button to your form, they are automatical ly coordinated so that only one option button can be selected at a t ime. You can check check i f an option button is selected or not with the Value property. Option button’s Value property has two sett ings: True i f the button is selected, and False i f not.

Line : - L ine control draws a straight l ine. You can change its properties to create graphical effects on forms. The l ine control ’s primary properties are X1, X2, Y1, and Y2, and those values form the coordinates of the l ine segment. You can format the l ine using properties l ike BorderStyle, BorderWidth etc.

Data Control : - Data control enable the user to connect to exist ing external databases. Other controls can then use the data control database l inks to automatical ly fil l in their

values. You can change the capt ion of this control using Caption property. To open a database using data control use DatabaseName property. The recordsource property is used to specify the table or recordsource to open. You can connect (Bound) a data control to another control l ike Textbox and display the contents of the fields in i t . To bound a control to data control , set the control ’s Datasource property to Data control ’s name and DataField property to the fieldname to be displayed in that particular control .

Page 10: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 10

RichText Box : - To add a RichText Box control , choose Project > Components and select the control name from the l ist and cl ick Apply button. To access text in a RichText box, you can use two properties: Text and TextRTF. The Text property holds the text in a r ich text box in plain text format l ike a text box, and TextRTF holds the text in Rich Text Format. The SelStart property is used to set the start and SelLength property is used to set the end of text selection. To make text bold, i tal ic, and underl ine you use SelBold, Sel I tal ic , and SelUnderl ine propert ies. You can also set indentation in r ich text boxes. The SelFontName and SelFontSize properties are used to specify the Font attr ibutes of

RichTextBox. The SelAl ignment property is used to specify the al ignment of selected paragraph in RichText box. Also you can apply different formats for the text in Rich Text box using different format options.

Form : - Form serves as a window that can customize and controls, graphics and pictures can be added to it .

Form WindowForm Window is used to design the different forms which is an appl ication. Each form can have many controls that perform various functions.

Project explorer:-Displays various elements of a project namely form, c lasses and modules. Al l the object that make up the appl ication are packed in a project . I t is possib le to develop any number of forms in a project. This window wil l help you to organize al l the files in your project . There is a View Object button and View code button which help to switch between object window (Form) and code window (form module) .The Project Explorer can be very useful when you’re working in a larger project and the IDE is fil led with design and code windows. To pick out the part of the project you want to work on, you only have to find it in the Project Explorer and double cl ick i t . Doing so brings the appropriate window to the foreground and, i f you’ve cl icked a form, opens that form in the Properties window. You can also add and remove items by r ight-c l icking them with the mouse in the Project Explorer. For example, you can add new forms, MDI forms, modules, c lass modules and so on just by r ight-cl icking the project’s icon in the Project Explorer. You can remove forms by r ight-cl icking them and selecting the Remove Item in the popup menu that appears, or you can save them to disk or switch between the form’s code window and the form itself . The Project Explorer gives us a valuable overview of our entire project, which is real ly very useful when a project gets large and contains many components.

Properties windowI t exposes the various characters of selected object. A property can be defined as "the named attr ibute of a control". Each and every form in an appl ication is considered as an

Page 11: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 11

object. Each object in VISUAL BASIC has its own properties such as color, s ize, name, caption, enabled, backcolor etc.When you select an object l ike a control in VISUAL BASIC using the mouse, that object ’s properties appear in the Properties window, you just find that property’s i tem in that window. I f you want to change that property, nothing could be easier- just cl ick the current sett ing. For properties that you set yourself , the current property value is highl ighted, and you just type in the new sett ing. I f the property can only be set to one of a specific range of propert ies, a downwards arrow wil l appear in the property sett ing box; c l ick this button to see the possible values this property can have.Al l this propert ies are displayed in properties window.

Form Layout windowVISUAL BASIC uses a new method for posit ioning forms on a user’s desktop, the Form Layout Window. This thumbnai l picture of the desktop shows you where the form wil l appear. You can drag the small form within the picture of the monitor to pick a new posit ion for i t . I f you move the form within your workspace, i ts posit ion on the Form Layout Window wil l not change. To give a form a new init ial location, just drag that form in the Form Layout window to that new location. You’ l l see the new screen posit ion of the form’s upper- left corner displayed in the toolbar. To resize the form, on the other hand, you have to use a form designer.

Form Designers and Code WindowsThe form designer displays the current form under design, and the code window displays the code for the program. Form designers are real ly just windows in which a part icular form appears. You can place controls into a form simply by drawing them after cl icking the corresponding control ’s tool in the toolbox. Code windows are simil iar ly easy to understand. You just place the code you want to attach to an object in the code window. There are two drop-down l ist boxes at the top of the code window. The left l ist lets you select the object to add code to, and the r ight l ist lets you select the procedure to add.

On line HelpWe can access the visual Basic help system from Help menu by sett ing.

ContentsIndexSearchOrFavorites

Which give help to user from MSDN(Microsoft Developer Network ) two very useful help related features that no longer wait for user)

Visual Basic includes fol lowing helps

Auto list members Auto quick info

Page 12: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 12

Auto l ist members is a t ime saving option that display a l ist box which contains the members (Propert ies or methods) that are avai lable in code window.

The Auto Quick info option displays the syntax of any functions or method. When one enters the name of procedure fol lowed by period space or open parenthesis.

Selecting IDE colors, Fonts, and Font SizesThe VISUAL BASIC IDE comes with al l kinds of preset colors-blue for keywords, green for comments, b lack for other code, and so on. VISUAL BASIC al lows you to do your own decorating. Just open the Opt ions item Tools Menu and cl ick Editor Format tab. Here are the text i tems whose colors you can select

Normal Text, Selection Text, Syntax Error Text, Execut ion Point Text, Breakpoint Text, Comment Text, Keyword Text, Ident ifier Text, Bookmark Text, Cal l Return Text

Aligning, Sizing, and Spacing Multiple ControlsVISUAL BASIC al lows you to al ign, s ize and give spacing between controls. Hold down the control key and cl ick al l the controls you want to al ign, make sure you have one control in the correct posit ion, and cl ick that one last . Sizing handles al lows you to resize the controls. To a l ign al l the selected controls, Choose Format>Align, select the type of al ignmentTo size the make same size item in Format menu, choose the appropriate item in the Make Same size sub menu.To space mult iple controls vertical ly or horizontal ly , select Horizontal spacing or vertical spacing and choose the submenu option.

Setting a Startup form or ProcedureVISUAL BASIC programs do not need to have any windows attr ibute a l l , in fact. That case is a l i tt le extreme, but there are t imes when you don’t want to start your program with code in a form. For example, you might want to display flash screen when your program first starts, without wait ing for the first form to load, and then switch to the form when it does load

Crating a Form-Free Startup procedure

To start a program from code not in any form, you add a subroutine named Main() to your program. Fol low these steps

1. Select the Properties i tem in Project menu to open Project Properties2. Cl ick the General tab, select Sub Main in the startup object drop down l ist,

and cl ick OK3. Select Add Module in Project menu, and double c l ick the Module icon in the

Add Module box that opens4. Add this code to the new modules General section in the code window

Sub Main()

End Sub

5. Place the code you want in the Main() subrout ine

Selecting the Startup Form

To specify the startup form for a project, just open the Project Properties box as we’ve done in the previous section and select the appropriate form in the Startup Object box, that form wil l Act as the Startup form.

Properties- Methods and Events:- All the controls in the tool box except pointer are objects in VISUAL BASIC. These objects have associated properties, methods and events.

PropertiesReal world objects are loaded with property. For E.g.: A flower is loaded with

certain color, shape and fragrance. Similar ly programming objects are loaded with property. A property is a named attr ibute of a programming object, which defines the characterist ic of an object such as size, color etc.E.g. : A text box accepts properties such as enabled, font, mult i l ine, text, v is ible, width etc.

The properties discussed above are design t ime properties that can be set using properties window. But certain propert ies cannot set at design t ime. E.g. : CurrentX, CurrentY properties of a form cannot be set at design t ime. These types of propert ies are cal led run t ime properties.

Page 13: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 13

Chapter 4

Learning Basic PropertiesLearning the Basic Properties

When you draw a Control , for E.g. : a TextBox, VISUAL BASIC sets several properties on each control to some default values. Before this form can be shown to the user, several of these propert ies values need to be changed so that the form wil l look correct . Many of the properties shown on the left s ide of properties window are self explanatory. Here is a quick description of some of the key properties.

(Name) This property is l isted in parentheses so that i t appears at the top of properties window. The Name property is how you wi l l access

this control in your VISUAL BASIC code. Al l controls have Name property.

ActiveControl Determines which control on the form or MDI form has focus and vis ible. This property al lows you to find the name of control and the type of control and access the properties of the control .

ActiveForm Returns which form on the screen or within an MDI form has the focus. A Form has the focus when it is selected or active form on the screen.

Alignment This property controls how text wi l l be displayed in the control . I t has three values: Left- Just ified, Right-Justified, Centered. You can

choose any of these from the drop down l ist.

Appearance This property al lows you to control whether the control is shown in 3document or shown flat. Windows 98 uses 3document controls

by default.

BackColor Sets the background color your control , VISUAL BASIC provides some preset system colors that you should use so that your

appl ication can use the colors set in Control Panel by the user

Bold The Bold property determines whether the text control led by a stdFont object is boldface. When it is boldface, the text appears thicker and darker. This property can be modified at run t ime or design t ime(using font d ialog).

BookMark This property is used to save a place in the recordset so that i t may be returned to later. I f the bookmarkable property of the recordset is true, then you can use the BookMark property to save the current place of the recordset and then use that value to return there later.

BorderStyle This property lets you add or remove a border around your control . I t has fol lowing values: 0 None 1 Fixed Single

Cancel Use this property to access the control by pressing Esc key. Used with Command Buttons. Pressing Esc key wi l l run the code associated with that control .

Caption Use this property to specify the text to be displayed as captions for controls l ike Command Button, Label etc. To add Hotkey for

your control you can use an ampersand ( & ) before the character in property. For Example, i f a Command Button has the

caption “&Add”, you can access this control at run t ime by choosing Alt + A

Col, Row Use these properties to determine or set the active column or row in a grid. Once active cel l is set , you can use other properties on

that cel l , such as text and cel lPicture. This property only readable and writable at run t ime.

Cols, Rows Use the Cols and Rows propert ies to read or set the total number of columns or rows in a grid control . These properties set up the

grid with enough cel ls to include the entire array.

Colwidth, RowHeight Use these properties to set the width and height of a column or row in a grid control . These propert ies are avai lable at run t ime.

ControlBox This property governs whether a control box appears in the top-left corner of a form. This property is read only at run t ime.

Copies The Copies property sets or returns the no. of copies to be printed. Not avai lable at design t ime. I f your printer does not support

Page 14: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 14

col lating, you should set the copies property to 1., or an error wi l l occur.

CurrentX, CurrentY These properties provide the horizontal(currentX) and vert ical (currentY) coordinates on a form , pr inter object etc.

these properties begin with the values set in the ScaleLeft and ScaleTop properties of the form or printer object. Anyt ime a drawn object appears on the form, or printer these properties change.

DatabaseName The DatabaseName property reads or sets the name and location of the database. Sett ing the value in the Data control ’s DatabaseName property whi le your program is running changes the database to which the control is connected. You must use the Refresh method to reopen the control after changing databases.

DataField The DataField property specifies what field a particular control wi l l bind to in the database. The developer sets the datasource

property to bind the control to an appropriately init ial ized data control . The datafield property then specifies which field in the specified data control ’s recordset wi l l be displayed in the bound control . This property can be read and write at design and run t ime.

DataMode This property controls i f the control works in bound or unbound mode. For e.g. A DBGrid can work in two modes. I t can be bound the tradit ional way to a Data control or you can fil l i t with data manual ly when it is in the unbound DataMode.

DataSource The DataSource property is always used in conjunction with the DataField property to bind a data aware control to a data

control on a form. The data control must reside on the same form as the object being bound and must be properly init ial ized to al low for binding. Init ial iz ing consists of sett ing a val id database name and a val id record source for the data control . At runtime, you may need to use the data control ’s Refresh method to establ ish the l ink to the database and act ivate the binding of the data aware controls.

Default Use this property to Access the control by pressing Enter Key. For E.g. You can set Default property of a Command Button to run the code associated with it by pressing Enter key.

DragIcon The DragIcon property indicates what icon wi l l be used as a pointer during a drag operation. This property is a useful way to indicate what type of drag operation is being init iated. I f used with the DragOver and DragDrop events, this property can change the pointer icon during a drag operat ion.

DragMode This property of a control indicates whether i t may be dragged in a drag operation without the use of a Drag method expression. Every control has an init ia l sett ing of manual. This indicates that the control may not normally be dragged. A drag operation may only be begun on a control with a manual sett ing by using the Drag method. With a control ’s DragMode property set to automatic, a drag operation automatical ly begins when the user presses and holds down a mouse button over the control .

DrawMode The DrawMode property determines what happens to a shape’s colors when the shape appears on the screen. This property modifies

the colors of F i l lColor, ForeColor, and BackColor propert ies of a form. You can read and write this property at design and run t ime.

DrawStyle This property controls the appearance of a l ine surrounding a drawn shape on a form, picturebox or printer object . An object’s

DrawStyle property defaults to producing a sol id l ine. You can change the sett ings to dashed l ine, dotted l ine, dash-dot l ine or dash-dot-dot l ine etc. when the DrawStyle property is invis ible, the l ine around shape does not appear. This property only affects a shape when it is being drawn. Any changes made to this property have no effect on those images that have already been drawn.

DrawWidth The DrawWidth property sets the width of l ines drawn of a form, picturebox or printer object. A value given to the DrawWidth property

represents the thickness of the l ine in pixels. When this value increases, the border around a drawn shape such as

circ le or square thickens.

Drive This property reads or sets the drive currently selected in a Drive l ist box. Directories on the selected drive can be displayed by an

associated directory l ist box. This property is useful for responding when the user changes the current drive.

Page 15: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 15

Enabled I f this property is set to True, the user can activate or focus on this control , i f this property is set to False user cannot access this

control at run t ime and is displayed in a gray shade.

Exclusive The Exclusive property of Data Control reads or sets whether a database is opened for s ingle-user or mult i -user access. Read and write attr ibute both design and run t ime..

FileName The Fi leName property enables your program to read the filename that is currently selected in a Fi le l ist box, or to set a new current file name. The str ing returned by this property only returns only the file name without drive and directory name. Use the path property to determine that information. This property can be set or read only at run t ime.

FillColor The Fi l lColor property sets the color of the interior of c ircles and boxes drawn in a container. Define an object’s Fi l lColor property either directly with hexadecimal number, or with QBColor or RGB functions. Changes to the Fi l lColor property has no effect on previously drawn objects.

FixedCols, FixedRows Use the FixedCols and FixedRows propert ies to read or set the number of fixed rows or columns on the left and top of a

grid. F ixed rows and columns are typical ly used for headings.

Font Displays a dialog box to specify Fontname, Font Style, Font S ize of the control . When selecting fonts, you need to remember that not every system has every font. However, you can always use certain fonts that are instal led with Windows l ike Times New Roman, Arial , Courier New etc.

FontCount The FontCount property indicates the number of printer or screen fonts avai lable, depending on whether you specify the screen or printer object. For screen fonts, the value returned encompasses al l the Windows Screen fonts as wel l as scalable fonts.

Fonts This property provides the name of one of the avai lable fonts of the screen or printer, depending on which of these objects you

specify and which font number you use with index. The index property may be changed whenever the act ive printer is changed or new font is added to the system with Control Panel.

Forecolor This is the Foreground color for the control . Any text in the control wi l l be shown in this color. The same rules apply to picking foreground colors as they do to background colors for the BackColor property

GridLines, GridLinesFixed Use this property to read or set the sty le of a grid’s gridl ines in the nonfixed and fixed cel ls. This property is avai lable at design t ime and readable at and writable at run t ime.

Height, Width By default Height and Width are given in twips. A twip is approximately 1/1440 inch. This property lets the user to set the Height and Width of the control

Icon This property determines the icon displayed on the screen when a form is in a minimized window state. Only avai lable with Form and MDI form, and the file must be in a standard icon format.

Index In large interface forms, you may have more controls of the same type. To void dupl ication of coding for controls VISUAL BASIC provides a feature known as control array. A control array lets you group ident ical controls the same name but able to access them by a number. The Index property holds a number for a control in a control array.

Interval The Interval property of a t imer control indicates the length of t ime to wait before processing the Timer event. This property may be

changes either at design or run t ime. Each t imer control ’s interval property is independent of the interval properties of other t imer control on the same form.

Italic This property determines whether the text control led by a StdFont object appears as Ital ic type. When it is i tal ic, the text is

s lanted, or scr ipt l ike. This property can be changed at design t ime (using Font Dialog) and run t ime.

Left, Top The Left and Top properties are the Horizontal and Vertical posit ions respectively of the upper-left point of the control .

Page 16: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 16

List The List property has two functions. F irst, i t can set the value of a l ist entry in a List or ComboBox; that is , specify an item to be

displayed on a List. Second, i t can read the current value (contents) of a l ist entry from a l ist or combo box. This property cannot be set at design t ime

ListCount The ListCount property is read at runt ime to determine the number of l isted items in a List, ComboBox, DriveList, Fi leList etc. This is

read- only property, and cannot be set by the program at design or run t ime.

ListIndex The List Index property returns the index number of the selected item in a l ist. The selected item is the one that has been previously

set by the program, or highl ighted by the user using arrow keys or by c l ick ing on the item. Assigning a value to the ListIndex property changes the selected item to the entry at the specified index. This property cannot be set at design t ime. I f no item is selected this property returns a value -1

Locked When this property is set to True, user can select the data in this control but cannot edit i t . I f you combine the Locked property

with a background color change, you can effectively use one window for two purposes. That is viewing and edit ing. By default this property is set

to False.

MaskColor A Mask color is a color in each graphic that VISUAL BASIC assumes to be transparent.

Max The Max property sets or returns the maximum value of a scrol lbar. This property can be set at design t ime, and set or read at

runtime. For a Scrol lBar control the maximum value is 32767, because it is an integer value.

MaxButton Controls whether the maximize icon button appears in the top-r ight corner of the form at run t ime. This property is readonly at run

t ime.

MaxLength This property sets the maximum amount of text the TextBox is al lowed to hold. I f this values is set to zero, the TextBox is not l imited.

MdiChild The MDIChi ld property defines whether a form is a regular, non-MDI form or MDI chi ld form. This property is read only at run t ime.

A Chi ld form can be only displayed inside a Parent form cal led MDI form.

Min The Min property of a Scrol lbar control sets or returns the minimum value. This property can be set at design t ime or run t ime. the

minimum value of a scrol lbar control is –32768 being an integer.

MinButton This property controls whether the minimize button on the form is displayed or not. This property is read only at run t ime.

MouseIcon I f you wish to show a custom icon whi le the cursor is over a control , set the MouseIcon property to that picture.

MultiLine The Mult iLine property lets you have mult iple l ines of text in your control l ike TextBox. By Default this property is set to false

that means you can enter only one l ine of text . When you set this property to true the Enter key can be used to add a new l ine to that TextBox.

MultiSelect This property lets the user choose more than one item at a t ime from a ListBox, ComboBox etc. I t has three values. 0 – Single Selection only (Default) , 1 – Simple mult iple select ion, 2 – Extended mult iple

selection.

Options The options property of a Data Control is used to set characterist ics of the Data control ’s Recordset. This property is avai lable to read and write attr ibute both design and run t ime.

Orientation The Orientation property sets or returns a value indicating whether your output wi l l be printed in portrait or landscape mode. This property is not avai lable attr ibute design t ime. The sett ings of this property are 1-vbPRORPortrait , 2-vbPRORLandscape.

Page The Page property returns the current page number in Printer object. You can use this property to put the proper page number on

each page. Not avai lable at design t ime, read-only at run t ime.

PasswordChar Use the PasswordChar property to setup a text box for password entry. By default, this property displays the character that the

Page 17: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 17

user types. I f you set anything other than empty str ing, i t wi l l display the first character contained in the property sett ing instead of character typed by the user. This gives the user visual feedback for each character typed without displaying the actual characters. Most windows programs use the asterisk ( * ) character as password character.

Path This property sets or reads the currently opened directory path in a directory l ist box, or the current directory in a file l ist box. At

design t ime this property is set to current default directory, and cannot be changed. This property can be set or read at run t ime.

Pattern The pattern property sets or reads the currently selected file matching pattern in a Fi le l ist box. Only files that match the pattern property are displayed in a file l ist box. By default the property is set to ( “ *.* ” ) . You can change the pattern property to display different file types using semicolon l ike *.BMP; *.GIF; *. JPEG; *.WMF

Picture Set the picture to be displayed on the control . Used with Image, Picture control , Command button etc.

RecordCount The RecordCount property al lows the appl ication to see how many records are in a recordset. However, this number is not accurate unt i l the entire recordset has been read. A MoveLast method wi l l guarantee al l the records have been read and the RecordCount property has the correct value.

Recordset The Recordset property sets or returns a Recordset object defined by a Data control ’s RecordSource property or an exist ing Recordset object. The Recordset object can be any of the three types defined for the Recordset object.

Recordsource The RecordSource property sets or returns the underlying source of the Data control ’s recordset. This source can be a table, a SQL statement, or a QueryDef object.

RightToLeft To set characters to RightToLeft for languages l ike Arabic and Hebrew.

RowSource The RowSource property provides the DBCombo and the DBList with their source recordset. The BoundColumn, BoundText, and

ListField are dependent upon this sett ing for their data. You must set the RowSource property at design t ime and cannot change it during runtime.

ScaleHeight The ScaleHeight property measures the usable height of a form, picturebox or printer object, excluding the border or t i t le bar of

the object. You can change this value at design t ime or run t ime. A new value becomes the user-defined proport ional measurement of the form, picturebox, or printer object.

ScaleLeft The ScaleLeft property sets or determines the left coordinate of the upper left corner of a form, picture box, or printer object,

excluding the border of the object.

ScaleMode This property indicates what unit of measure to use for the form, picturebox or printer object. Unless the scaleMode property is

0, al l the dimensions of the forms, controls, and graphical objects use this measurement. The default unit is Twips, which equivalent to 1/1440 inch. The vb constants you can used for this property are 0-vbUser, 1- vbTwips, 2-vbPoints, 3-vbPixels, 4-vbCharacters, 5-vbInches, 6- vbMil l imeters, 7-vbCentimeters.

ScaleTop This property sets or reads the coordinates of the top of a form, picturebox or printer object excluding border or t i t le bar of the

object.

ScaleWidth This property sets or determines the usable width of a form, MDI form, Picturebox or printer object excluding the border and t it le bar. This width is measured in the units indicated by scalemode property.

ScrollBars This property lets you select horizontal , vert ical , or both scrol lbars for this control

Selected The selected property lets you determine which items in a mult iple selection l ist are selected. This property is an array of True and

False values, with one entry for each item in the List.

SelLength The SelLength property is used to set or return the number of selected characters within an object . Characters can be selected by the user usual ly for edit ing. Your program can also select a

Page 18: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 18

portion of text in a TextBox. This property can be set and read at run t ime only.

SelStart The SelStart property is used to set or return the start ing posit ion of selected text within an object. I f there is no selected text, this

property sets or returns the posit ion of the box’s insertion point.

SelText The SelText property replaces or returns the currently selected text within a Control . Users can select text either by using mouse or

keyboard or by a program action

Size The Size property of the StdFont object determines the point s ize of text control led by the StdFont object. This property can be

modified at design t ime or run t ime.

Sorted The Sorted property specifies at design t ime whether or not the items in the l ist or combo box are to be automatical ly sorted by VISUAL BASIC.

Stretch The Stretch property determines whether the image control stretches to fit the picture or the picture stretches to fit the image

control . You can read and write with this property at both run t ime and design t ime.

Style The Style property sets the sty le of an object. For a ComboBox style properties are 0 – Dropdown Combo, 1 – Simple Combo, 2 – Dropdown List and for a CommandButton this property can be used to set the Style Standard or Graphical . Set this property to specify the style of a Command Button It has two values. Standard and Graphical . Set the Graphical property i f you have to d isplay pictures on Command button.

TabIndex You can use this property to determine the order in which the user moves through the screen using Tab key. Change this property

in which order you want to focus on controls start ing from Zero.

TabStop I f the TabStop property is False, the user cannot reach this control by pressing Tab Key. You can use this property for controls such

as PictureBox controls being used as containers in which you do not want the user to accidental ly Tab into.

Text This property contains the text d isplayed in control . As default VISUAL BASIC always put the name of the control in this property.

ToolTipText This property lets you provide quick, helpful information about what a control does by putt ing it in the ToolTipText property. I f the

user pauses over a control , the ToolTip text wi l l be displayed. This property is handy to provide more information to the user about the control .

TopIndex This property reads or sets the topmost vis ible row in a L istBox or the List part of a ComboBox. This property a l lows you to

programmatical ly determine what rows in a List are vis ible. This property is only read and write at run t ime.

Value Sets the value for the controls l ike CheckBox, Opt ion button, Scrol lBars etc. i t may be integer value, True / False or any predefined value set.

Visible This property indicates whether the control should be vis ible to the user at run t ime. It has two values True and False

Page 19: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 19

Chapter 5

MethodsMethods

Method is an action that can be performed on objects. In other words, in Object Oriented Programming (OOP), a method is a connected or bui lding procedure, a b lock of that can be involved to impart some action on a particular object .

Some Basic Methods

AddItem : - The AddItem method adds an item to the l ist of a ListBox, ComboBox control etc. When the l ist box and combo box objects first display, no items are assigned to the l ist. You must use the AddItem method to create l ist entr ies. When this method executes, the value of the str ing expression specified by the Item$ argument is added to the l ist. You can specify the exact p lacement of the new item in the l ist by providing the Index% argument. I f you supply the index number, VISUAL BASIC wi l l add one to the index number of the item that current ly holds the specified index, and al l those items that fo l low it . The new item is then added to the l ist at the specified index. Supplying an index number inserts the new item at that posit ion in the l ist. I t does not replace the item that is currently at that posit ion. I f you supply an Index value, i t must be greater than or equal to 0 and not greater than the value of ListCount property

E.g. :Pr ivate Sub Form_Load ( )

Combo1.AddItem “Orange”Combo1.AddItem “Apple”Combo1.AddItem “Grape”Combo1.AddItem “Mango”

End Sub

AddNew : - The AddNew method is used to add new rows to a Recordset object. I t can be used with any Table type or Dynaset type recordset. Once you appl ied this method to a recordset object, an edit buffer is created with the empty record in i t . You can then enter the required data into the fields and final ly use the Update method to save the data to the recordset. I f you are using a counter field it wi l l automatical ly increase during Update.

E.g. :Pr ivate Sub CmdAdd_Cl ick ( )

rs.AddNewrs!Item=Text1.Textrs!Qty=Val(Text2.Text)

rs.UpdateEnd Sub

Arrange : - Use the Arrange method on an MDI form to automatical ly arrange al l MDI chi ld forms contained within i t . It has four values. 0 – vbCascade, 1 – vbTi leHorizontal , 2 – vbTi leVert ical , 3 – vbArrangeIcons.

E.g. :Pr ivate Sub mnuArrange_Cl ick( Index As Integer )

Select Case Index

Case 0 frmMDI.Arrange vbCascadeCase 1frmMDI.Arrange vbTi leHorizontalCase 2frmMDI.Arrange vbTi leVerticalCase 3frmMDI.Arrange vbArrangeIcons

End Select

End Sub

BeginTrans : - The BeginTrans method starts a new Transaction within a particular Workspace object’s col lect ion. Transactions are used to help ensure that changes to the database are complete in al l respects before being final ized. See Also CommitTrans and Rol lBackTrans methods.

Circle : - This method generates a curved shape on an indicated object on the screen or printer. This method can create a variety of curved objects including c ircles, el l ipses (ovals) and arcs. The object on the screen to be drawn on is a Form, PictureBox, or Pr inter Object. I f the Keyword Step fol lows the word Circle, then X and Y coordinates are

Page 20: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 20

relat ive to the values of CurrentX and CurrentY properties. Omitt ing the word Step means that X and Y are relat ive to the top- left corner of the object. The values of X and Y define the posit ion of the center of the shape. The Radius argument defines the Circles radius. Al l these measurements are done in unit of measure defined by containers ScaleMode property. The color argument sets the color of l ine surrounded. To skip an argument in the middle of the syntax, include a comma ( , ) for each argument. Don’t end a Circ le method with a Comma.

E.g. :Pr ivate Sub CmdCirc le_Cl ick( )

Stat ic Start As Double

If Abs(Start )> 6.283 Then

Start=0

End I f

Circle ( 400, 400) , 100 ,QBColor(3) , Start , -6.283 , 1

Start=Start – 0.785

End Sub

Clear : - The Clear method gives you a an easy way to completely clear FlexGrid, l ist box or ComboBox. This method is also use with Err object which clears al l the property sett ings of an Err object. The Clear method with a Cl ipboard object c lears the contents of Cl ipboard

E.g.:Pr ivate Sub CmdClear_Cl ick( )

Cl ipboard.ClearCombo1.ClearList1.Clear

End Sub

Close : - for OLE objects, Use this method close an object and terminate its connection to the appl ication that provided it . This method can be also used to c lose an object l ike Database, Table etc.

E.g. :Pr ivate CmdClose_Cl ick ( )

OLE1.CloseMydb.Close ‘where Mydb is a Database objectMyrs.Close ‘Where Myrs is a Recordset object

End Sub

Cls : - The Cls method removes drawn graphics or text from an object on the screen. This method changes the CurrentX and CurrentY properties of a form or P ictureBox. This method has no effect on a Form’s controls and their contents. I t only affect any drawn graphics.

E.g. :Pr ivate Sub CmdClear_Cl ick ( )

Pr int “Hel lo Welcome”MsgBox “Printed”ClsMsgBox “Cleared”

End Sub

Commit : - This method attempts to commit the current transaction. This method fai ls i f any of the objects involved in the transaction cal led SetAbort or DisableCommit without later cal l ing EnableCommit or SetComplete. See also Transact ions, Begin, Rol lBack

CommitTrans : - This method ends the transact ion set and attempts to store the transactions to the database. Once you successful ly used this method, you can no longer undo changes made during the transact ion. See also BeginTrans, Rol lBackTrans methods.

Copy : - This method al lows you to copy the object in an OLE container control to Cl ipboard.

E.g. :Pr ivate Sub CmdCopy_Cl ick ( )

OLE1.Copy

Page 21: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 21

End Sub

CreateDatabase : - This method is used to create a new instance of a native Jet database.

E.g. :Pr ivate Sub CmdCreate_Cl ick( )

Dim WS As WorkSpaceDim DB As DatabaseSet WS=DBEngine.Workspaces(0)Set DB=WS.CreateDatabase ( “C:\MYDATA\CLENTS.MDB”, dbLangGeneral)

End Sub

CreateWorkSpace : - The CreateWorkSpace of the DBEngine object is used to create addit ional workspaces in the particular instance of the DBEngine. When using this method you must provide the name, user, and password arguments. The Workspace object created has a l i fespan of that part icular session and dies when that session of the DBEngine ends. Once you creates a WorkSpace, you cannot change any of i ts properties.

E.g. :Pr ivate Sub Form_Load ( )

Dim WS as WorkspaceDim MUSER as Str ingMUSER=”NETS”Set WS=DBEngine.CreateWorskSpace ( “Executive” , MUSER , “PASSWORD” )

End Sub

Delete : - The Delete method is used to delete a record in a Dynaset or Table type Recordset object or to delete a stored object in a col lection of a parent object . The Delete method of OLE container control lets you delete an object.

E.g. :Pr ivate Sub CmdDelete_Cl ick ( )

I f Not Rs.Nomatch Then

Rs.Delete

End I f

End Sub

Drag : - This method init iates or ends a Drag Operat ion. With this method, you can manipulate controls on the screen when a control ’s DragMode property is manual. This method typical ly appears in the MouseDown event of the control to be dragged.

E.g. :Pr ivate Sub Picture1_MousDown( Button As Integer, Shift As Integer, X As Single, Y

As Single )Picture1.Drag

End Sub

EndDoc : - The EndDoc method ends the current document and sends output to the windows printing routines. Use this method when you have completed al l of the print ing for a document.

E.g. :Pr ivate Sub MnuPrint_Cl ick ( )

Pr inter.Pr int “Hel lo”Printer.Pr int “Welcome”Printer.Pr int “to NetS”Printer.EndDoc

End Sub

Execute : - The Execute method of a Database object or QueryDef object is used to run an act ion Query or SQL statement

E.g. :Pr ivate Sub mnuAdd_Cl ick( )

Mydb.Execute( “Insert into Stock ( Item, Qty) Values ( ‘TV’ , 100 ) “)

End Sub

Page 22: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 22

FindFirst , FindNext , FindPrevious , FindLast : - Used to Search for an item in a Dynaset or Snapshot type recordset object .

E.g. :Pr ivate CmdSearch_Cl ick ( )

Rs.FindFirst “ Item= ’TV’ ”If Rs.Nomatch=False Then

Text1.Text=Rs!QtyEnd I f

End Sub

GetData : - Retr ieves graphics information (pictures) from Cl ipboard area. This method is used to copy graphic data from cl ipboard to a specific object . The type of data requested is specified by format% parameter. This parameter is an integer with the value of 2-(vbCFBitmap), 3-(vbCFmetafile), 8-(vbCFDIB), or 14-(vbCFEMetafile).

E.g. :Pr ivate Sub Command1_Cl ick ( )

Picture1.Picture=Clipboard.GetData ( vbCFBitmap )

End Sub

GetFormat : - The GetFormat method returns an integer value (True or False) indicating whether the requested data type is stored in the Cl ipboard. The Different Data formats for the GetFormat method includes 1-vbCFText, 2-vbCFBitmap, 3-vbCFMetaFi le, 8-vbCFDIB, 9-vbCFPalette, 14-vbCFEMetafile, 15-vbCFFi les

E.g. :Pr ivate Sub Command1_Cl ick ( )

TextStored=GetFormat(vbCFText)Print TextStored

End Sub

GetText : - The GetText method retr ieves text information from the c l ipboard. This method copies the specified type of text from the cl ipboard into the specified object. The type of data requested is specified by the format% parameter. This parameter is an integer with a value of 1-(vbCFText), &HFFFFBF00-(vbCFLink), or &HFFFFBF01-(vbCFRTF).

E.g. :Pr ivate Sub Command1_Cl ick ( )

Text1.Text=Clipboard.GetText(vbCFText)

End Sub

GoBack : - Used to instruct a Hyperl ink container to go to the last web page in i ts history l ist.

E.g. :Pr ivate Sub Command1_Cl ick ( )

UserControl .HyperLink.GoBackEnd Sub

GoForward : - Used to instruct a hyperl ink aware container to go to the next web page in i ts history l ist.

E.g. :Pr ivate Sub Command1_Cl ick ( )

UserControl .HyperLink.GoForward

End SubHide : - The Hide method makes an active and vis ible form disappear from the screen and is the same as sett ing the form’s vis ible property to False. This method does not remove from memory, i t only hides the form. You can use Show method to display a hidden form. A hidden form can respond to coded events and any result ing property changes.

E.g. :Pr ivate Sub Command1_Cl ick ( )

Form1.Hide

End Sub

KillDoc : - The Ki l lDoc method immediately ends the current print job and the printer driver resets the printer. Using this method you can now cancel a print job before it

Page 23: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 23

starts. I f you have Print Manager running with background printing enabled, Ki l ldoc deletes the current print job and prevents the printer from printing anything.

E.g. :Pr ivate Sub cmdCancelPrint_Cl ick( )

Pr inter.Ki l lDoc

End Sub

Line : - The Line method draws a l ine or box shape object on the screen or printer. This method can create number of shapes, including straight l ines, squares, rectangles, polygons, and tr iangles. The object drawn on may be form, picturebox, printer etc.

E.g. :Pr ivate Sub cmdLine_Cl ick ( )

Form1.Line (100,100)-(300,300), Qbcolor (5)

End Sub

Move : - The Move method moves an object to another location on the form. You must specify the left and top properties of the object to move. The Move method of a Recordset object provides the appl ication with the capabi l i ty to navigate the RecordSet in large steps.

E.g. :Pr ivate Sub cmdMove_Cl ick( )

Text1.Move 100,200

End Sub

MoveFirst , MoveLast , MoveNext , MovePrevious : - These methods of a Recordset object provide the appl ication with the abi l i ty to navigate the RecordSet. The MoveFirst method moves to the first row of the Recordset. The MoveLast method moves to the last record. The MoveNext method moves to the next record in the recordset. The MovePrevious method moves to the previous record in the RecordSet.

E.g. :Pr ivate Sub cmdMoveFirst_Cl ick( )

rs.MoveFirst ‘ where rs is a recordset object

End Sub

NewPage : - The NewPage method ends output for the current page and sets up the next page for subsequent output.

E.g. :Pr ivate Sub cmdNext_Cl ick ( )

Pr inter.NewPage

End Sub

OpenConnection : - This method is used to open an ODBC connect ion.

Syntax:Workspace.OpenConnection ( datasource, [prompt, [readonly, [connect,

[options]]]])

Datasource is the name of the datasourcePrompt is used to specify the characterist ic of ODBC prompt which has the values rdDriverPrompt, rdDriverNoPrompt, rdDriverComplete, rdDriverCompleterequired etc.

Readonly specifies whether the datasource is to be open as read only or not

Connect is the connect ion str ing

Options – set to rdAsyncEnable i f you want to execute commands asynchronously

Page 24: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 24

OpenDatabase : - The OpenDatabase method is used to open a database in the specified session and returns a reference to the Database object variable that represents i t . The fo l lowing example wi l l describe about the method and its arguments.

Syntax:

Set databaseobject=workspace.OpenDatabase( dbname [, options[, readonly [ , source]]])

dbname is the database name with ful l d irectory path, options determines how the database is to be opened that is in exclusive (True) or Share (False) mode, readonly has two values True and False, source is a str ing expression with the ODBC connect arguments.

E.g. :Pr ivate Sub Form_Load( )

Dim db As DatabaseDim WS As WorkSpaceSet WS=DBEngine.Workspaces(0)Set db=WS.OpenDatabase(“C:\ABC\XYZ.MDB”)

End Sub

OpenRecordset : - The OpenRecordset method creates a new Reordset object and appends it to the Recordset col lect ion. The Fol lowing example wi l l describe about i ts arguments and options

Syntax:

Set recordsetobject=databaseobject.OpenRecordset(source[, type[, options[, Lockedits]]] )Set recordsetobject=object.OpenRecordset(source[, type[, opt ions[, Lockedits]]])

Recordsetobject is a variable representing a recordset object type, Databaseobject is an open database object. Object is a variable of QueryDef, Recordset or TableDef type that references a val id object . Source is a str ing specifying the source of recordset , i t may be a table or Query name in the database or a SQL statement. Type determines the type of Recordset, that is Dynaset, Table, or Snapshot type. Options is an integer specifying the characterist ics of the new Recordset object, the values for options is dbDenyWrite, dbDenyRead, dbReadonly, dbAppendOnly, dbForwardonly, dbRunAsync etc. Lockedits is used to lock for the New Recordset i ts values are dbReadonly, dbPessimist ic, dbOptimistic etc.

E.g. :Pr ivate Sub Form_Load( )

Dim db As DatabaseDim WS As WorkSpaceDim rs As RecordSetSet WS=DBEngine.Workspaces(0)Set db=WS.OpenDatabase(“C:\ABC\XYZ.MDB”)Set rs=db.OpenRecordset(“Select * from Stock”,dbOpenDynaset)

End Sub

PopupMenu : - The PopupMenu method displays a popup menu. These menus can appear anywhere on the form, and are general ly context sensit ive. Most appl icat ion display them when the alternate mouse button ( normally r ight mouse button ) is cl icked. These type menus are used to display options appropriate for the object the user c l icked. Popup menus display when you use PopupMenu method on a form. You specify what menu you want to display, and give the method opt ional parameters for exactly where it d isplays and how it behaves.

E.g. :Pr ivate Sub Text1_MouseDown ( Button As Integer, X As Single, Y As Single)

If Button=vbRightButton ThenPopupMenu menuwindows, vbPopupMenuRightButton

End I f

End Sub

Print : - The Print method puts a str ing of text or numeric value at an object’s current posit ion. Each print method identifies the object to place the str ing on by preceding it with the Name property of the form or p icture box, or Pr inter or Debug. A print method may contain mult iple expressions separated by Spc(n), Tab(m), commas, and semicolons.

E.g. :Pr ivate Sub Form_Click( )

Pr inter.Pr int “This Text” , “Has Commas”, Pr inter.Pr int “WelCome”Printer.EndDoc

End Sub

Page 25: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 25

PrintForm : - This method sends a copy of a VISUAL BASIC form to the windows print ing routines. This can be an easy way to take advantage of VISUAL BASIC’s form design capabi l i t ies in creating printed forms, and to format printed output so that i t is identical to what is shown on the screen.

E.g. :

Pr ivate Sub cmdPrintForm_Click( )

AddressForm.PrintForm

End Sub

Refresh : - The Refresh method forces any changes affecting a control to be reflected in i ts status or display immediately. The Refresh method is useful in two situat ions. First , because windows is a mult itasking program, it is possible to make a change to a control that is not reflected on the screen because background processing is in progress. Using Refresh method causes any changes to the specified control to be reflected immediately. Second, the refresh method can be used to cause the Drive, Directory, and Fi le l ist boxes to update their l ists. You specify the refresh method with the name of control

E.g. ;Pr ivate Sub cmdRefresh_Cl ick( )

Fi leList1.RefreshEnd Sub

RemoveItem : - The RemoveItem method deletes an item from the l ist box, or combobox indicated by the index argument. When an item is removed from a l ist or combo box always specify the correct index number greater than or equal to zero (0) and less than Listcount property of the object. You can use the ListIndex property to determine the index of current ly selected object.

E.g. :Pr ivate Sub cmdRemove_Cl ick( )

List1.RemoveItem List1.ListIndexEnd Sub

Requery : - The Requery method is used to update the data in a RecordSet object by running the underlying query again. This method ensures that your recordset’s data is val id to be running the underlying query, again repopulat ing the Recordset with the latest data. This method has the same effect has closing the recordset and opening it again. This method only works with Dynaset and Snapshot type recordsets whose restartable property is true.

E.g. :Pr ivate Sub cmdRefreshData_Cl ick( )

Rs.Requery

End Sub

RollbackTrans : - The Rol lBackTrans method ends a new Transaction set and restores the database to i ts condit ion prior to the start of the Transact ion. Transactions are used to help ensure that changes to the database are complete in al l respects before being final ized. See Also CommitTrans and BeginTrans methods.

Scale : - The Scale method determine the l imits of the coordinates used on a form, picturebox, or printer object. This method defines the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop propert ies in one expression instead of four. In this method the first two coordinates specify the horizontal and vertical coordinates of the upper-left corner of the object i .e. , ScaleLeft and ScaleTop. The numbers in the next set represent the lower-r ight corner of the same object i .e. , ScaleWidth and ScaleHeight.

E.g. :Pr ivate Sub Form1_Resize( )

Form1.Scale (0,0)-(500,500)Text1.Move 0,0 ,ScaleWidth,(scaleHeight/2)

End Sub

Scroll : - The Scrol l method scrol ls a Grid control , Scrol lbar control etc either Horizontal ly or vertical ly.

E.g. :Pr ivate Sub cmdScrol l_Cl ick ( )

Grid.Scrol l 1,1

End Sub

Page 26: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 26

Seek : - The Seek method is used in a Table type Recordset object to find, using an index object, the row containing the specified criter ia. You can seek only on a field or fields that are indexed. The seek method is the fastest method locat ing data in your database. The seek method finds the first row that matches your cr iter ia depending on the direct ion of seek. i f a match is found, the NoMatch property of the recordset returns False

Syntax:

Recordsetobject.Seek comparison, key1, key2…E.g.:

Pr ivate Sub cmdSearch_Cl ick( )

Rs. Index=”ss” ‘ where ss is an index created for the table on a particular fieldRs.Seek “=”, ‘TV’If rs.Nomatch=False Then

MsgBox “Found”

End i f

End Sub

SetData : - The SetData method places graphic information in the Cl ipboard object in the specified format. The type of data send to the c l ipboard is specified by the format% parameter. This integer has the values 2- vbCFBitmap, 3- vbCFMetafile, 8-vbCFDIB, 9-vbCFPalette, 14-vbCFEMetafile

E.g. :Pr ivate Sub Command1_Cl ick ( )

Cl ipBoard.SetData Picture.Picture,vbCFBitmap

End Sub

Setfocus : - The SetFocus Method gives a control or form the focus. The control and form arguments of a SetFocus operat ion must be the Name property of a Form or control . Only those controls and forms with Enabled property set to True may be given the Focus.

E.g. :

Pr ivate Sub Text1_KeyPress( KeyAsci i As Integer)

Text2.SetFocus

End Sub

SetText : - This method places text information into the Cl ipboard object in the specified format. The type of data is specified by format% parameter. This parameter is an integer with values &HFFFFB00- vbCFLink, &HFFFFB01-vbCFRTF, 1-vbCFText.

E.g. :Pr ivate Sub cmdCopy_Cl ick( )

Cl ipboard.SetText Text1.Text

End Sub

Show : - The Show method lets you load and display a form on the screen, or display an already loaded form. A form remains in memory unti l i t is removed using an Unload statement or unti l the program ends.

E.g. :Pr ivate Sub mnuSales_Cl ick( )

FrmSales.ShowEnd Sub

Page 27: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 27

TextHeight , TextWidth : - These methods help you posit ion text on a form, picturebox, or printer object by tel l ing you what the height and width of the text str ing would be i f displayed using the current font and point s ize. A value returned by the TextHeight and TextWidth methods represents the size of the text str ing using the unit of measure specified in the ScaleMode property. Both these methods are avai lable at runtime only.

E.g. :Pr ivate Sub Form_Resize( )

AutoRedraw=TrueFont.Name=”Arial”Font.S ize=9Display$=”A str ing for demo”

Do While TextWidth( display$) < ScaleWidth –TextWidth ( “ “)Font.S ize=Font.Size+0.5

Loop

X=TextWidth(display$)Y=TextHeight(display$)EndY=Abs(ScaleHeight / Y ) +1

For H= 1 to EndYPrint Display$CurrentY=CurrentY+YCurrentX=0

NextEnd Sub

Update : - The Update method of a Recordset object saves the contents of the edit buffer to the Recordset object. This method is only val id for Dynaset and Table type recordsets, in addit ion the updatable property of the recordset must be true. This method is used to complete the process started with the AddNew or Edit methods. I f you init iate an AddNew or Edit without using a subsequent Update method, your changes wi l l be lost when you move the record pointer or issue another AddNew or Edit method.

E.g. :Pr ivate Sub cmdSave_Cl ick( )

Rs.AddNewRs!Item=Text1.TextRs!Qty=Val(Text2.Text)Rs.Update

End Sub

Zorder : - This method places an object in front of or behind other objects within i ts graphical level. You can read and write with this method at both design and run t ime. the constants used for this method are 0-vbBringToFront, 1-vbSendToBack.

E.g. :Pr ivate Sub Timer1_Timer ( )

Stat ic I As IntegerImage1(I) .Zorder vbBringToFrontI=I+1If I=10 Then I=0

End Sub

Page 28: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 28

Chapter 6

Event Driven ProgrammingEvent driven programming

VISUAL BASIC programs are bui lt around events. Events are various things that can happen in a program.

In an event driven appl ication the program statement are executed only when a particular event cal led the specific part of the code that is assign to the event.

E.g. : A text box control supports various events l ike change, c l ick, mouse move , key press etc.

These are l isted in the property drop down l ist in the code window. Several events are associated with d ifferent controls and focus some of the events are common and few being specific to each control .

VISUAL BASIC Events

VISUAL BASIC recognizes different events. Some events are recognized by many objects, some by only a few or even just one object. The fol lowing l ists the different events and their meaning.

Event Description

Activate Form just received focusAfterAddFi le Fi le added to current projectAfterChangeFi leName Fi lename changedAfterCloseFi le Fi le c losedAfterRemoveFi le Fi le removed from the projectAfterWriteFi le Fi le savedBeforeLoadFi le Before a file is addedChange Control ’s value changedClick Control just got c l ickedConnectAddIn Add-in added to VISUAL BASICDblCl ick Control just got double cl ickedDeactivate Form just lost focusDisconnectAddIn Add-in removed from VISUAL BASICDoGetAddFi leName User selected Add Fi leDoGetNewFi leName User saving file or projectDoGetOpenProjectName User opening a new projectDragDrop Control just got droppedDragover Another control just got dragged over this controlDropDown User c l icked the down arrow on combo boxError External ly caused database errorGotFocus Control just received the focusInit ial ize Object createdKeyDown User pressed a KeyKeyPress User pressed a KeyKeyUp User released the KeyLinkClose DDE l ink just c losedLinkError DDE l ink has an errorLinkExecute DDE l ink just received an external commandLinkNotify DDE l ink data has changed in a Noti fy style l inkLinkOpen DDE l ink has just openedLoad Form has just loadedLostFocus Control just lost focusMouseDown User just pressed mouse buttonMouseMove User just moved mouseMouseUp User just released mouse buttonObjectMove OLE object moved or resizedOLECompleteDrag Source object is notified that drop action occurredOLEDragDrop Source object is dropped onto a controlOLEDragOver Source object got dragged over this controlOLEGiveFeedback Provides a drag icon feed back to the userOLESetData Sets Data when a Source object is droppedOLEStartDrag Sets the type of data format and drop effect the source

object supports when drag is started

Paint Control just got uncoveredPathChange Path property just changedPatternChange Pattern property just changedQueryUnload Form is about to UnloadReposit ion Current record just changedRequestChangeFi leName User specified new file nameRequestWriteFi le Prompt before project savedResize Form just changed sizeRowColChange Grid’s act ivecel l just changed

Page 29: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 29

Scrol l Scrol lbar thumb just movedSelChange New cel l selected in gridTerminate Object was destroyedTimer Timer interval finishedUnload Form unloadingUpdated OLE object changedVal idate Current record about to change

Some Basic Events

Activate : - The Act ivate Event occurs when an object becomes activated either by code or by the user.E.g. :

Pr ivate Sub Form1_Act ivate( )

Form1.width=4000

End Sub

Change : - The change event init iates an action when the user changes the value of an object’s primary property, such as by making a selection or entering data.E.g. :

Pr ivate Sub Text1_Change( )

End SubThis event occurs i f the property changes by a user action, the program’s code, or by dynamic data exchange events.

Click : - Use the Cl ick event to react to the user’s cl icking a checkbox, command button, or option button. This event is also defined as sub procedure that is named with the control ’s name

E.g.:Pr ivate Sub Command1_cLick ( )

Text1.text=”Hel lo”

End Sub

DblClick : - Use the DblCl ick event to react to the user’s pressing the left or r ight mouse button twice in quick succession.

E.g. :Pr ivate Sub List1_DblCl ick()

Msgbox “You cl icked twice”

End Sub

Deactivate : - The Deactivate Event occurs when an object becomes deactivated either by code or by the user.E.g. :

Pr ivate Sub Form1_deact ivate( )

Msgbox “Hel lo”

End SubDragDrop : - A DragDrop event contains the act ions that occur at the completion of a drag-and-drop operat ion over another control . Drag-and-drop operations terminate with either a Drag method expression or the release of a mouse button. When the user releases the mouse button whi le the mouse pointer is over a control , this is known as the drop part of a drag-and-drop operation.E.g. :

Pr ivate Sub Picture2_DragDrop( Source As Control , X As Single, Y As Single)

Picture2.Picture=Source.PictureSource.Picture=LoadPicture(“”)

End Sub

Page 30: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 30

DragOver : - A DragOver event contains the actions that take place when a drag operation moves the mouse pointer over a control before the user releases the mouse button. These actions do not necessari ly terminate a drag-and-drop operation, but the DragOver event can serve this purpose.E.g. :

Pr ivate Sub Picture2_DragOver( Source As Control , X As Single, Y As Single, State As

Integer)Select Case State

Case 0 , 2Picture2.BackColor=QBColor(7)Source.DragIcon=LoadPicture(“C\xyz. ico”)

Case 1Picture2.BackColor=Qbcolor(15)Source.DragIcon=LoadPicture(“C\xyz. ico”)

End Select

End Sub

DropDown : - The DropDown event specifies what actions wi l l be taken when the user opens the l ist portion of a drop-down combo box. This provides your program with an opportunity to tai lor the l ist entr ies based on information that may not have been avai lable at an earl ier t ime, such as the activity the user is performing or preferences previously expressed by the user.E.g. :

Pr ivate Sub Combo1_DropDown( )

If Combo1.ListCount < 10 Then

Combo1.AddItem “Hel lo”

End i f

End Sub

GotFocus : - The GotFocus event specifies what act ions to take when a control or form receives the focus. A control or form receives the focus either by a user action ( Pressing Tab or Mouse Cl ick) or by code using the SetFocus method.E.g. :

Pr ivate Sub Text1_GotFocus( ) Text1.BackColor=QBColor(15)

End Sub

Initialize : - The Init ial ize event occurs when a form, MDI form, or Class module is first loaded into memory using Load statement for Form or with New Keyword for class. This event is used to init ial ize any information used by a form or object. Init ial ize occurs before load event and occurs only once during the l i fet ime of a form or object . E.g. :-

Pr ivate Sub Form_Init ial ize( )

Me.Data1.DatabaseName=”C:\ABC\XYZ.MDB”Me.Data1.Datasource=”Name and Addresses”

End Sub

KeyDown : - Use the KeyDown event for low-level keyboard handl ing. I t reports the current status of the keyboard when a key is pressed and this event’s control has the focus.E.g. :

Pr ivate Sub Text1_KeyDown ( KeyCode As Integer, Shift As Integer)

Text1.Text=KeyCode

End Sub

Table of KeyCode

KeyCode VB.Constants Meaning

&H1 vbKeyLButton (uncommon)&H2 vbKeyRButton (uncommon)&H3 vbKeyCancel (uncommon)&H4 vbKeyMButton (uncommon)&H8 vbKeyBack [B]&H9 vbKeyTab [T]&HC vbKeyClear [L]&HD vbKeyReturn [ENTER]&H10 vbKeyShift [SHIFT]

Page 31: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 31

&H11 vbKeyControl [CTRL]&H12 vbKeyMenu [ALT]&H13 vbKeyPause [PAUSE]&H14 vbKeyCapital [CAPS LOCK]&H1B vbKeyEscape [ESC]&H20 vbKeySpace [SPACEBAR]&H21 vbKeyPrior [PAGE UP]&H22 vbKeyNext [PAGE DOWN]&H23 vbKeyEnd [END]&H24 vbKeyHome [HOME]&H25 vbKeyLeft [ ]

&H26 vbKeyUp [ ]&H27 vbKeyRight [ ]&H28 vbKeyDown [ ]&H29 vbKeySelect (Uncommon)&H2A vbKeyPrint [PRINT SCREEN]&H2B vbKeyExecute (Uncommon)&H2C vbKeySnapshot Uncommon)&H2D vbKeyInsert [ INSERT]&H2E vbKeyDelete [DELETE]&H2F vbKeyHelp (Uncommon)

vbKeyA through vbKeyZ are the same as their ASCII equivalents, A through Z.vbKey0 through vbKey9 are same as ASCII equivalents , 0 through 9

&H60 vbKeyNumpad0 Numeric pad 0&H61 vbKeyNumpad1 Numeric pad 1&H62 vbKeyNumpad2 Numeric pad 2&H63 vbKeyNumpad3 Numeric pad 3&H64 vbKeyNumpad4 Numeric pad 4&H65 vbKeyNumpad5 Numeric pad 5&H66 vbKeyNumpad6 Numeric pad 6&H67 vbKeyNumpad7 Numeric pad 7&H68 vbKeyNumpad8 Numeric pad 8&H69 vbKeyNumpad9 Numeric pad 9&H6A vbKeyMult iply Numeric pad *&H6B vbKeyAdd Numeric pad +&H6C vbKeySeparator (uncommon)&H6D vbKeySubtract Numeric pad –&H6E vbKeyDecimal Numeric pad .&H6F vbKeyDivide Numeric pad /&H70 vbKeyF1 1&H71 vbKeyF2 2&H72 vbKeyF3 3&H73 vbKeyF4 4&H74 vbKeyF5 5&H75 vbKeyF6 6&H76 vbKeyF7 7&H77 vbKeyF8 8&H78 vbKeyF9 9&H79 vbKeyF10 0&H7A vbKeyF11 !&H7B vbKeyF12 @&H7C vbKeyF13 (uncommon)&H7D vbKeyF14 (uncommon)&H7E vbKeyF15 (uncommon)&H7F vbKeyF16 (uncommon)&H90 vbKeyNumlock [NUMLOCK]&H91 n/a $

KeyPress : - The KeyPress event intercepts ASCII (American Standard Code for Information Interchange) keystrokes when this event’s control has the focus. This lets the program audit the user’s input byte by byte. This can be useful for val idating data input and altering the user as soon as an inval id character is entered. E.g. :

Pr ivate Sub Text1_KeyPress(KeyAsci i As Integer)

If KeyAsci i =13 ThenText2.SetFocus

End I f

End Sub

Page 32: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 32

Possible Values for KeyAscii argument

Valid Character KeyAscii Code

[Ctr l]+A through [Ctr l]+Z ASCII code of the character[ENTER] and [Ctr l]+[ENTER] 13 and 10[BACKSPACE] and [Ctr l]+[BACKSPACE] 8 and 127[TAB] 9Any Printable Keyboard character ASCI I code of the Character

KeyUp : - The KeyUp event is used for low- level keyboard handl ing. I t reports the current status of the keyboard when a key is released and this event’s control has the focus.E.g. :

Pr ivate Sub Text1_KeyUp (KeyCode As Integer, Shift As Integer)

Label1.Caption=Format$(KeyCode, “###”) ‘show last key released

End Sub

Meanings of KeyCode argument in KeyUp are same as in KeyDown event

Meanings of Shift values in the KeyUp Event

Shift vbConstants Meaning

1 vbShiftMask [SHIFT] key was pressed2 vbCtrlMask [CTRL] key was pressed3 vbAltMask [ALT] key was pressed

This event is a complement to KeyDown event. Every t ime the user released a pressed key on the keyboard, including [SHIFT] , [CTRL] or [ALT] keys, the object that currently has the focus receives this event. Before this event occurs, a KeyDown event wi l l occur atleast once, with an identical KeyCode value. Where the KeyDown event may be executed several t imes when a user holds a key down, the KeyUp event may be executed only once per keystroke, when the user releases the key. This makes this event perfect for low- level handlers when you wish to disable the automatic repet it ion of keys on the keyboard.

Load : - The Load event loads a form into memory and specifies what actions occur when it loads. This event init ial izes the form and any related variables when the form loads. A loaded form is in memory but cannot be seen by the user. A form’s Load event takes place in three ways. First , any form loaded at program startup init iate a Form_Load event. Second, VISUAL BASIC generates a Form_Load event when a form is loaded programmatical ly, using Load statement. Third, any change or reference made to a property of an “unloaded” control or form loaded the form and tr iggers the Form_Load event.E.g. :

Pr ivate Sub Form1_Load( )

Combo1.AddItem=”Apples”Combo1.AddItem=”Orange”Combo1.AddItem=”Grape”

End Sub

LostFocus : - The LostFocus event specifies what actions to take when a control or form loses the focus, either because the user selected another object or the code reassigned the focus. The LostFocus event could occur in different way. A user may choose another control using mouse or by pressing tab key. A SetFocus method also give the focus to another control . This event can contain actions that may change the appearance of controls or forms to s ignify that this control has lost the focus.E.g. :

Pr ivate Sub Text1_LostFocus( )

Command1.ForeColor=H00FF000&Command1.SetFocus

End Sub

Page 33: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 33

MouseDown : - The MouseDown event occurs when any button on the mouse is pressed. Unl ike the Cl ick event, the MouseDown event can be used to determine not only that a mouse button has been pushed, but which button was pushed. You can also determine whether [SHIFT], [CTRL] or [ALT] key was being held down when the mouse button was cl icked. This wi l l al low for a variety of different kinds of interact ions with your appl ications. I t suppl ies four arguments that indicate status of the mouse attr ibute the t ime the event is cal ledE.g.:

Pr ivate Sub Form_MouseDown ( Button As Integer, Shift As Integer, X As Single, Y As S ingle)

If Button=vbLeftButton Then

StartX=XStartY=Y

End I fEnd Sub

Meanings of Shift Values in MouseDown event

Shift vbConstants Meaning

1 vbShiftMask [SHIFT] key was pressed during MouseDown2 vbCtrlMask [CTRL] key was pressed during MouseDown4 vbAltMask [ALT] key was pressed during MouseDown

The X and Y arguments are single precis ion variables that correspond to the mouse pointer’s posit ion within the related form or control attr ibute the t ime the event was cal led. Here X is horizontal and Y is Vertical coordinates.

MouseMove : - The MouseMove event defines the actions to take when the user moves the mouse pointer. You can find out where the mouse pointer was when it was moved, what button ( i f any) was down, and whether the [SHIFT], [CONTROL] or [ALT] key was being hold down.E.g. :

Pr ivate Sub Form_MouseMove ( Button As Integer, Shift As Integer, X As Single, Y As S ingle)

If Shift And vbShiftMask Then

Line ( 100, 100) – ( X, Y )

End I f

End Sub

MouseUp : - The MouseUp event occurs when any button on the mouse is released. You can also find out where the mouse pointer was when the button was released. You can also determine whether [SHIFT], [CTRL] or [ALT] key was being held down when the mouse button was released.E.g. :

Pr ivate Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As S ingle)

If Button = vbLeftButton Then

EndX= XEndY=Y

End I f

End Sub

Meaning of the Button values in MouseUp event

Button vbConstants Meaning

1 vbLeftButton Left button was pressed2 vbRightButton Right button was pressed4 vbMiddleButton Middle button ( i f avai lable ) was pressed

Page 34: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 34

Paint : - The Paint event defines what act ions take place when uncovering a previously obscured part of a form or p icture box. Either restoring a minimized form or uncovering an obscured form tr iggers a Paint event. This event only appl ies to generated graphics and does not affect the appearance of the controls on a form. This event may contain act ions that place graphics objects on the screen. This event reproduces the same graphic image or images on a form or picture box. Some times, i t can produce a total ly new image.E.g. :

Pr ivate Sub Form_Paint ( )

Stat ic Num as IntegerX=ScaleWidth/2Y=ScaleHeight/2Radius=Scalewidth/4Fi l lStyle=0Num=Num+1

Select Case Num

Case 1Fi l lColor=QBColor(0)Circle(X,Y), Radius , , -6.283 , -1.571

Case 2Fi l lColor=QBColor(1)Circle(X,Y), Radius , , -1.571 , -3.142

Case 3Fi l lColor=QBColor(2)Circle(X,Y), Radius , , -3.142 , -4.713

End SelectEnd Sub

QueryUnload : - The QueryUnLoad event lets you react to an attempt to Unload a form. This al lows you to perform any necessary c leanup l ike saving unsaved data and possible query the user before any form is Unloaded. This event specify what actions take place when an attempt is made to c lose a form. Using this event gives the user a chance to stop the ent ire unloading process before any forms are unloaded.

E.g. :Pr ivate Sub Form_QueryUnLoad( Cancel as Integer, UnLoadMode as Integer)

If ChangeText thenSaveChange=MsgBox( “ Document Changed… Save?”, _

vbexclamation+vbYesNoCancel)

Select Case SaveChange

Case vbCancelCancel=True

Case vbYesCal l F i leSave(1) ‘ Cal l the procedure to save file

Case vbNoCancel=False

End SelectEnd i f

End Sub

Resize : - This event specifies what actions take place when the user resizes a form or picture box, or when the form or picture box first becomes vis ib le. This event can be tr iggered by anything that brings the object into the users s ight or changes its s ize. When your program changes the WindowState, Vis ible, Height, or Width properties of a form. VISUAL BASIC a Resize event.E.g. :

Pr ivate Sub Form_Resize ( )

Form1.width=2000

End Sub

Scroll : - This event is raised when the scrol lbar of an object has been moved. This event can be used to monitor the scrol l ing of the ActiveX document.E.g. :

Pr ivate Sub HScrol l1_Scrol l ( )

Text1.Text=HScrol l1.Value

End Sub

Page 35: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 35

Terminate : - This event occurs when a form or object is destroyed. You destroy a form or object by sett ing it to nothing, which you do after unloading it in the case of a form. Terminate is the last event in the l i fet ime of an object. Terminate event occurs after Unload event. Use the Terminate event for final cleanup.E.g. :

Pr ivate Sub Form_Terminate( )

ReDim NADTable( 0 ) ‘ free up any al located memory

End Sub

Timer : - The t imer event contains the actions that take place when a t ime equal to the interval value of the t imer control has elapsed. This event tr iggers everyt ime the interval of t ime elapses unti l the t imer control is disabled. This event is only associated with Timer control .E.g. :

Pr ivate Sub Timer1_Timer ( )

Stat ic a As IntegerIf A Then

Picture1.Picture=Picture2.PictureElse

Picture1.Picture=Picture3.PictureEnd I fA= Not A

End Sub

UnLoad : - The Unload event procedure specifies what actions to take when a form is unloaded. Al l forms close automatical ly at the end of the program. An unload statement can also close a form. One use of this event is to reset the information on the form before removing it from memory. Another use of the Unload event can be to give the user a final chance to prevent ending the program.E.g. :

Pr ivate Sub Form_UnLoad( Cancel As Integer )

IF MsgBox(“Are Sure to Exit?”, vbYesNo) = vbYes Then

UnLoad Me

ELSE

Cancel = True

END IF

End Sub

Page 36: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 36

Chapter 7

Working With Forms & ProjectWorking with forms

The form is the one of the most basic object in VISUAL BASIC, in which the appl ication is developed. A form is a window that contains appl icat ion code and has other objects placed on it to create the user interface. At the top of the form is the t i t lebar, which displays the form's t i t le. At r ight in the t i t lebar is the Control box, including minimize, maximize and Close buttons. The main area of a form-the area where everything takes place- is cal led the c l ient area. In general , VISUAL BASIC code works with controls in the cl ient area and leaves the rest of the form to VISUAL BASIC. Also you can give different types of borders to your form.

A form may fil l the entire screen or have other forms contained within i t or may be a dialogue box. VISUAL BASIC init ial ly includes a default form, form 1. You can change the properties of a form to ident i fy the purpose. A form has its own property, events and methods.

These are few special property appl ied only to a form,

I) Border stylea) None b) Fixed single :- A s ingle fixed width border is shown.c) Sizable : - The default sett ing. User can resize the form.d) Fixed double:- A double fixed width border is shown.e) Fixed tool window:- Used for tool bar that may be floating only the

t i t le bar and close box are vis ible in a reduced size.f) Sizable tool window:- Same as fixed tool window but borders are

resizable.

II) Caption : - The t it le for the window is store in caption property. When the form is minimized, the caption appears below the form item.

II I) Control box : - Determines whether the control box is avai lable by cl icking the upper left corner. True / false.

IV) Icon : - Specifies the icon for the window in upper left corner.

V) Max button : - Whether the max button is shown or not.

VI) MDI Child : - Specifies i f this window is must be shown within a mult iple document interface (MDI) true / false.

VII) Min button : - Indicates whether the minimize button is shown or not. True / fa lse.VIII) Start up position ; - used to posit ion your window. You can pick a start ing posit ion from the fol lowing,

(a) Manual : - Any posit ion must be done.

(b) Center owner :- The form should be shown in the center of i ts container.

(c) Center Screen : - The form should be shown in the center of user screen.

(d) Window default :- Lets window to design where the form should be shown.

e) Window state:- Indicates whether the window is shown normally, minimized or maximized.

Displaying form : - (a) Show method:- Used to display the form object . E.g. : To display form 2,

Form2.show

(b) Load statement:- I t used to load a form or control into memory but does not display it .

E.g. :-Load form2

Hiding and unloading:-

Hide method:- The hide method hides a form

E.g. :- Form2.hide.

Unload statement:- The unload statement remove the form to display and release its memory.

E.g. : unload form2.

Page 37: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 37

Setting run time and design time propertiesMany properties can be set at run t ime or design t ime. At design t ime, the

controls are added to a project and their propert ies are set using properties window.

During run t ime, to set a property , you must write the relevant code.

Object.propertyname= value

E.g.:- Text1.Text = "Nets"Command1.caption = "close"List 1.vis ible = fa lseCheck 1.value = 1

At the left s ide of the assignment statement, object.property name is identi fy ing the object and property to be set. The value on the r ight s ide gives a new sett ing for the object. When a program resets a property at run t ime, the new sett ing overwrite the value of the current sett ing.

Moving and Sizing Controls using CodeSometimes it 's necessary to move or resize the controls in a form as a program is running, but for some reason, many VISUAL BASIC programmers think you can only do that at design t ime. In fact, you can do it at runt ime easi ly.Al l controls have these properties avai lable at design t ime or runt ime to set their location and dimensions.

Top-The y coordinate of the top left of the control . Left-The x coordinate of the top left of the control . Width-The width of the control . Height-The height of the control .

You can change al l these sett ings interact ively to move or s ize a control in a form. Note that al l measurements are in Twip (1/1440 of an inch) by default , and that the origin (0,0) in a form is at upper left.You can also use a control 's Move( ) method to move a control to a new location:

Object.move left, [top, [width, [height]]]

E.g.:Pr ivate Sub Command1_Cl ick( )

Command1.Width= 2 * Command1.WidthCommand1.Height= 2 * Command1.HeightCommand1.Move (Command1.Left + 500)

End Sub

Showing and Hiding Controls in a FormYou can use the Visible property to show or hide controls at run t ime. You can set this property also at design t ime.

Object.Vis ible=True

E.g.:Pr ivate Sub Command1_Cl ick( )

Text1.Vis ible= Not Text1.Vis ible

End Sub

Measurements in FormsThe default measurement units for forms are twips.

You can get the dimensions of a form's cl ient area with these properties

ScaleWidth-The width of the cl ient area. ScaleHeight-The height of c l ient area. ScaleLeft-The horizontal coordinate of upper left of c l ient area. ScaleTop-The vertical coordinate of upper left of cl ient area.

And you get the overal l dimensions of the form using these properties

Width-The width of the form Height-The height of the form Left-The horizontal coordinate of upper left of Form. Top-The vertical coordinate of upper left of the Form.

You can also use the ScaleMode property to set a form's coordinate system units-you don't have to use twips. Here are the possible values for ScaleMode.

Page 38: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 38

0-User defined 1-Twips (1/1440 of an inch) 2-Points (1/72 of an inch ) 3-Pixels 4-Characters (120 twips horizontal ly, 240 twips vertical ly) 5-Inches 6-Mil l imeters 7-Centimeters

Creating Forms in CodeNew forms are simply new objects in VISUAL BASIC. To declare a new form based on a form you already have, say Form1, you just use Dim. Next, you create the new form with the New keyword, Final ly you show it using Show method.

Private Sub NewForm_Click( )

Dim NewForm As Form1Set NewForm=New Form1NewForm.Show

End Sub

Developing an application An appl ication can be created with the project. A project is a col lection of files that are used to bui ld an appl ication.

Writ ing a VISUAL BASIC program has two steps.

1) Visual programming step:- i t involves designing an appl ication with various tools that come along with VISUAL BASIC package.

2) Code programming step:- This involves writ ing programs in code window.

Saving a project : - Choose file save. When a project is saved two files are saved; namely project file and form file. The project file has extension VBP and contains the information that VISUAL BASIC uses for bui lding the project . The form file contains information about the form and has .FRM extension. I f you have a standard module within your project i t is saved in separate file with .BAS extension.

Running the project:- You can run your project using any of the fol lowing methods

Press F5, Cl ick the run button on the standard tool barChoose start from run menu on the step tool bar

Creating an execut ive file: -Choose file>make EXE file command. As the appl ication is converted into exe the user can run it on any other windows program.

Ending an appl icat ion:-The End statement is used to terminate the execute the appl ication it unload al l the form from memory.

Page 39: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 39

Chapter 8

VISUAL BASIC LanguageElements of Visual Basic Syntax

Every Program uses a no .of basic bui lding blocks. These elements wi l l be in every program you write in one way or another.

1) Literals :- a Literal is the simplest bui lding block you wi l l see in your VISUAL BASIC program. It is either a piece of text or a number that you use in your programs. Every program wil l have some l i terals in i t . Text l i terals are known as str ings, and are always surrounded with double quoted when used in a program

E.g.:- Print “ This is Text “Here, “This is a Text “ is a str ing. Numeric l i terals do not require double quotes

within your programs.

E.g.:- Print 3456

2) Constants:- A constant can be used to replace a l i teral that is d irect ly in your code. Using a constant you can change the value of constant and al l of the uses of that constant wi l l use the correct value. Constants are treated just l ike l i terals by Visual Basic. In order to use a constant, you must declare it . Declaring a constant s imply means that you are tel l ing Visual Basic about i t . The Const keyword is used to declare a constant.

E.g.:- Const MyConstant =”Hi”

3) Data Types:- Each kind of data you use in Visual Basic is known as Data Type. Each data type has l imits to the kind of information and the minimum and maximum value it can hold. In addit ion some types can interchange with some other types. By default VISUAL BASIC variables are variant data types. The variant data type can store numeric, date/t ime, str ing data's. When a variable is declared a data type is suppl ied for i t that determines the kind of data they can store. The fundamental data type in VISUAL BASIC are variant, integer, long, single, double, str ing, currency, byte and Boolean. Each data type has l imits with the kind of information and the minimum and maximum value it can have.

Type Value range

1. Byte 0 to 255

2. Boolean true or false

3. Integer -32768 to 32767

4. Long -2,147,483,648 to 2,147,483,647

5. Single -3.402823* 103 to -1.401298*1045 (for -ve value)1.401298*10-45 to 3.402823*1038 (for +ve value)

6. Double -1.79*10308 to -4.94*10-324 (for -ve value)4.94*10-324 to 1.79*10308 (for +ve value)

7. Date January 1, 100 to December 1, 9999

8. Str ing 0 to approx. 2 b i l l ion characters

9. Currency 922,337,203,685,477.5908 to 922,337,203,585,477.

590710. Decimal -79,228,162,514,264,337,593,543,950,335 to

79,228,162,514,264,337,593,543,950,335

4) Variables:- Variables are used for storing values temporari ly. A defined naming strategy as to be fol lows whi le naming a variable.

A variable name must begin with an alphabet and should not exceed 255 characters. I t must be unique with in the same scope. I t should not contain any special characters l ike %, &, ! Etc.

Visual Basic declaring statementsDim - Using Dim alone creates variants. Use the As keyword to specify variable typePrivate - Makes variable avai lable only in the current form/modulePubl ic - Makes variable global-variable is avai lable to the rest of programReDim - Real locates storage space for dynamic array variables

Page 40: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 40

Stat ic - Variable preserves its value between procedure cal lsType - Declares a User type

Declaring a variable:-There are many ways for declaring a variable in VISUAL BASIC. Depending on where the variables are declared and how they can be use by our appl icat ion. The different ways of declaring variables are

1. Implicit declaration:- Declaring a variable tel ls VISUAL BASIC to reserves space in memory. It is not a must that a variable should be declared before using it . Automatical ly when VISUAL BASIC encounters a new variable, i t assigns default variable type and value. This is cal led implicit declarat ion. This type of declaration is easier for the users, i t is advisable to declare them expl icit ly.

The variables are declared with a DIM statement to name the variable and its type. The As type clause in DIM statement al lows to define the data type or object type of the variable. This type of declaration is expl icit declaration.

SyntaxDIM variable [as type]

1. Dim ab as integer2. dim ab ->variant 3. dim ac as str ing4. dim ac as Boolean

Using Option Explicit statementi t may be convenient to declare variables impl ic it ly; but i t can lead to errors that

may not be recognized at run t ime. In VISUAL BASIC to prevent errors of this nature, we can declare a variable by adding the fol lowing statement to the general declaration segment

Option Explicit.

This forces the user to declare a l l the variables. This statement checks in the module for usage of any undeclared variables and reports an error to the user. The user can thus recti fy the error. This statement can be placed in general declaration sect ion of each module using fol lowing steps.

Choose tools > options > editCheck require variable declaration

Selecting Variable TypesThere’s a wide range of data types. Visual Basic has a large number of data formats. The variant type deserves special mention, because it ’s the default variable type. I f you don’t declare a type for a variable, i t is made a variant.

E.g. : Dim ab

Be careful of variants-they waste t ime because VISUAL BASIC has to translate them into other data types before using them, and they also take up more space than other data types.

Converting between Data TypesVISUAL BASIC supports a no. of ways for converting from one type of variable to another-in fact, that’s one of the strengths of the language. The possible conversion statements and procedures are

VISUAL BASIC Data Conversion functions

ANSI value to str ing ChrStr ing to lowercase or Uppercase Format, LCase, UCaseDate to serial number DateSeria l , DateValueDecimal number to other bases Hex, OctNumber to str ing Format, StrOne data type to another CBool, CByte, CCur, CDate, CDbl, CDec,

CInt, CLng, CSng, CStr, CVar, CVErr, F ix, IntDate to day, month, weekday, or year Day, Month, Weekday, YearTime to hour, minute or second Hour, Minute, SecondString to ASCI I value AscStr ing to number ValTime to serial number TimeSerial , TimeValue

Scope of variables:-A variable is scoped to procedure level ( local) or module level depending on how it

is declared. A variable is declared in general declaration sect ion or form and is avai lable to al l the procedures. This is cal led module level variable declarat ion.

Page 41: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 41

Local variables are recognized only in the procedure in which they are declared. They can be declared with dim and static key word. I f we want a variable to be avai lable to al l the procedures with in the same module or al l procedures in appl ication, a variable is declared with broader scope.

Local variablesA local variable is one that declared inside a procedure. I t is only avai lable to the code inside the procedure and can be declared using dim statement. Once a procedure is executed, the values of i ts local variable are losed and the memory used by this variable can be reclaim. Variable that are declared with keyword dim exist only as long as the procedure executed.

Static variableStat ic variables are not reinit ial ized each t ime VISUAL BASIC involves a procedure and thus retains or preserves values even when a procedure ends.A stat ic variable is declared as given below.

Stat ic ab as integer.

Module level variableA module level variable is avai lable to al l the procedures in module. They are declared using publ ic or private key words.

Publ ic ab as integerPrivate xy as str ing

Declaring a variable with publ ic key word makes it avai lable throughout the appl ication even for other modules. At the module level there is no difference between dim and private, but private is referred because it is easier to read.

Publ ic variables should not be declared within a procedure. Publ ic variables in different modules can have the same name and they can be differentiated in code.

E.g. : i f a publ ic integer variable ab is declared in both form 1 and Module 1 of a project, i t can be referred as form1.ab and module1.ab.

same variable cannot be used for different data types.

Global ScopeMost powerful of the scope .To define a variable as global . the publ ic declarat ion statement is used. The syntax of the publ ic statement is same as Dim except the keyword publ ic

Public VS local variableA variable can have the same name, d ifferent scope.E.g. : we can have a publ ic variable named X within a procedure. We can declare a local variable X. reference to the name X within the procedure would access the local variable and reference out the procedure would access publ ic variable.

Verifying Data TypesYou can change a variable’s type with ReDim in VISUAL BASIC, assign objects to variables using Set, and even convert standard variables into arrays. VISUAL BASIC has a number of data verificat ion funct ions, and you can use these funct ions to interrogate objects and determine their types.

Function Description

IsArray( ) Returns True i f passed an arrayIsDate( ) Returns True i f passed a dateIsEmpty( ) Returns True i f passed variable is uninit ial izedIsError( ) Returns True i f passed an error valueIsMissing( ) Returns True i f value was not passed for specified

parameter in procedure cal lIsNul l( ) Returns True i f passed Nul lIsNumeric( ) Returns True i f passed Numeric valueIsObject( ) Returns True i f passed an Object

E.g. :Dim x As IntegerX=100Print IsNumeric(x)

5) Operators:- Visual Basic has a number of operators to work with numeric,Boolean,and text data.

a) Assignment operator:- The equal sign (=) is used to assign the value of a constant, l i teral , or variable to another variable. Literal and cannot be on the left s ide, they should be on r ight s ide in using assignment operator.

b) Arithmetic Operators: -Arithmetic

Page 42: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 42

i ) Addit ion operator ( + ):- the addit ion operator is the plus s ign commonly used in addit ion. E.g. :- Pr int 3 + 4.5 = 7.5

i i ) Subtraction operator ( - ) : - the Subtraction operator is the same as the one you use for subtraction, the minus sign. This character is also used to show negative numbers

E.g. :- Pr int 8 - 4.5 = 3.5

i i i ) Mult ipl ication operator ( * ) : - The asterisk is used to mult iply two variables, constants, or l i terals and produce a result.

E.g. :- Pr int 3 * 4.5 = 13.5

iv) Divis ion operator ( / ) : - The forward slash is used to divide two variables, constants, or l i terals.

E.g. :- Pr int 8 / 4 = 2

v) Integer Div ision operator ( \ ) : - integer div ision operator rounds the two numbers to integer values and produces the result as an integer. Standard decimal divis ion does not round or truncate the operands or the result.

E.g. :- Pr int 5.6 \ 2 = 3 here this process rounds 5.6 to 6, and divis ion produces the result 3

vi) Exponent Operator ( ^ ) : - The exponent operator is used to ra ise a number to a power.

E.g. :- Pr int 2 ^ 3 = 8 (2 * 2 * 2)

vi i ) Modulus operator ( mod ):- The modulus function calculates this value by producing the remainder left when dividing the two integers. When used with no integers, the function rounds both operands before processing the result .

E.g. :- Pr int 11 mod 3 = 2

C) Comparison Operators:- VISUAL BASIC provides a number of operators to use for comparisons of numbers and str ings. Using one of these operators with two variables, constants, or l i terals creates a logical expression. The operators l isted below can be used to compare two quantit ies.

Operator Meaning

= is equal to<> is not equal to> is greater than>= is greater then or equal to< is less than<= is less than or equal to

D) Concatenation Operator:- Concatenation is the process of putt ing two str ings together. concatenation is a very useful feature. To concatenate two str ings, you use the ampersand ( & ) operator.

E.g. :- ab= “IC” + “ES”Print ab = “ICES”

E) Logical Operators:- Logical operators are used to perform operat ion between values or expressions that result in either True or False. You can use logical operators to combine mult iple expressions.

i) Not operator:- The Not operator s imply reverses a True to False and vice versa.

E.g. :- Pr int Not (3>4) text1.font.bold= Not text1.font.bold

i i ) And operator: - The And operator is used to combine two logical expressions and produce a result. When you use the And operator, both expressions must be True in order to get a True result.

E.g. :- I f a=5 And c=10 then Print “Ok”

i i i ) Or operator: - The Or operator wi l l produce a True result i f either condit ion is True. I f both condit ions are False, that is the only t ime the Or operator wi l l produce a False result.

E.g. :- I f a=5 Or c=10 then Print “Ok”

iv) Xor: i f a=10 Xor b=5 then combines two expressions. The entire expression is considered true, I f the two expressions are not both true and false.

v) Eqv(equivalent): combines two expressions. Both expressions must be true or fa lse for the entire expression is to be true.

Page 43: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 43

vi) Imp : combines two expressions. The entire expression is true except when the first expression is true and second expression is fa lse.

Page 44: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 44

Chapter 9

ModulesModules:-

1) Modules:- Code in VISUAL BASIC is stored in the form of modules. The three kinds of modules

are form modules, standard modules and class modules.

A simple appl ication may contain a s ingle form and the code is written in that form module itself. As the appl icat ion grows addit ional form are added and there may be common code to be executed in several forms. To avoid the dupl ication of code, a separate module containing a procedure is created. That implements the common code. This is a standard module. Class modules are the foundat ion of object or iented programming(OOP). New object can be created writ ing code in c lass modules.

To add a Standard module Choose Project Add ModuleTo add a Class module Choose Project Add Class Module

Each module can contain,

Declarations : - may include constant, type, variable and al l procedure declaration.

Procedure : - A sub function, or property procedure that can contain p ieces of code that can be executed as a unit .

Component parts of a VISUAL BASIC projectComponent File Extension Description

Standard Module .BAS contain project code, general ly accessible through your project

Form Module .FRM, .FRX design and code user interface

Class Module .CLS define methods and properties of a custom object

ActiveX Control .OCX add addit ional functions to the Toolbox

ActiveX Server .EXE, .DLL Add funct ional ity of OLE 2.0

Insertable Objects Add objects from an OLE 2.0

Object L ibrary .OLB, .TLB obtain information about OLE automation objects

Resource Module .RES store str ing, b itmap, and other compiled data.

ActiveX Designers .DSR, .DSX Add visual interfaces for tasks that might require a great deal of coding

Standard Module : - Standard Modules with the extension .BAS, contain declarations of constants, types and variables, as wel l as procedures and functions. Standard Module contain only codes. Module level declarations and definit ions in a standard module are by default Publ ic , which means that constants, variables and procedures declared within a standard module are by default accessible by code in other modules and forms. Some items you may want to put in a standard module are API declarations, Constants, user-defined types, variables and general and external procedures.

Form Module : - Form modules, with the extension .FRM, are the foundat ion of your appl ications user interface. They contain al l your text fields and controls, including any property sett ings of these controls. Forms also can contain constant and variable declaration, procedures, and event procedures for the various form and control events. More complex appl ications may have several forms, each with its own form module. Declarat ions in a form module are private by default , which means that constants, variables, and procedures in a form module are not avai lable to code outside that form unless you expl ic it ly declare them as publ ic.

Class Module : - Class modules, with the extension .CLS, are similar to form modules, except that they have no visual component. You can use class module to create your own objects. Class modules can include code for methods and properties associated with an object that you define, but they cannot include their own events.

Page 45: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 45

ActiveX Controls : - ActiveX controls, with extension .OCX, contain information VISUAL BASIC needs to provide new features and controls to your appl ication’s toolbar. An ActiveX control can be a variation on an exist ing Microsoft Windows Control , such as a modified version of the gauge control , or i t can be a completely new category of control , such as graphics import filter that lets you import many types of graphical images. An ActiveX control is just another term for an OLE object. I t is based on Microsoft COM (Component Object Model) architecture and is self -registering object. You can use ActiveX controls in both 16bit and 32 bit version of VISUAL BASIC. In general a lmost al l new ActiveX controls are 32 bit. You can add or remove an Act iveX control from your toolbox by using Project > Component Dialog box. To add a control select the check box against the control name and to remove it deselect the checkbox. I f the control is in use with in your project, which means that the control is placed on your form, you cannot remove it from Toolbox.

ActiveX Exe : - ActiveX Exes, with extension .EXE, were formerly known as OLE automation servers. They al low you to use the methods and properties exposed by OLE 2.0 objects in your projects. Al l edit ions of VISUAL BASIC some with powerful set of OLE server objects. You can also create your own objects or obtain them from Third-party developers. You’ l l need to add a reference to the object appl ication to your project before you can use any of i ts c lasses. Use Projects > References menu command. From the dialog select the object name and press OK.

ActiveX DLL : - An Act iveX DLL offers the same benefits of true dynamic l ink l ibraries (DLL), with the exception of making Declare statement cal ls against them. In order to take advantage of them, use the DLL through OLE automation. Once an ActiveX DLL is properly registered in your Windows Registry, i t can be added to your appl ication l ike any other OLE object. Any OLE-compliant appl ication can take advantage of this DLL as wel l . The advantage of an ActiveX DLL over an out-of-process OLE server is that an Act iveX DLL loads itself in the processing space of the c l ient appl ication. Be cautious, however, an unstable ActiveX can cause instabi l i ty within the appl ication

Insertable Objects : - They do not have file extensions. They exist within object Appl icat ions such as Microsoft Excel or Word for Windows, that support a visual user interface. As with controls, you can add these insertable objects directly onto your VISUAL BASIC form to create an integrated solut ion. You can add or remove an insertable object to your Toolbox by using Project > Components Dialog box.

Object Libraries : - An object l ibrary file, with extension .OLD or .TLB, provides information about avai lable OLE automation objects to OLE automation control lers, such as VISUAL BASIC appl ications. Executable Fi les (EXE) and Dynamic Link L ibrary (DLL) files can also contain object l ibraries. To add an object l ibrary to your VISUAL BASIC development environment, use the Project > References dialog. To view the referenced object l ibraries, use the Object Browser by select ing it from View Menu.

Resource Files : - a Resource Fi le, with extension .RES, can contain bitmaps, text str ings, and other data. Using the resource file increases your appl ication’s performance and capacity because it al lows you to load str ings, images, and data into memory when needed, rather than when the form or module is loaded. Resources are useful for isolating str ings and images from source code, which makes it easier to local ize an appl ication. Resource files are compiled resource code; therefore, when you add a resource file to your program, the View Form and View Code buttons in the project Explorer are disabled when the file is selected. To create a resource file, you need to use a development product that has a resource editor and compiler, such Microsoft Visual C++.

ActiveX Designers : - An Act iveX designer, with an extension of .DSR, provides a v isual design interface for tasks that might require a lot of coding. An Act iveX designer is l ike a form module or c lass module. ActiveX designers are based on the Component Object Model (COM). The COM is what al l ActiveX and OLE technologies are based on it . I t is a standard that defines how appl ications expose objects. Similar to a resource file, an ActiveX designer is loaded only when it is needed. To include ActiveX designers in your project Select Designers tab from Project > Component dialog.

Procedure and control structures.VISUAL BASIC offers different types of procedures to execute small sections of coding in appl ication.

Procedures:VISUAL BASIC programs can be broken in to smaller logical components cal led procedures. Procedures are useful for condensing repeated operations in a program. A procedure used in a program can be act as bui lding blocks for other programs with sl ight modifications.

Sub proceduresA sub procedure can be placed in Standard, Class and Form modules. Each t ime the procedure is cal led the statement between sub and End sub are executed. Subrout ines are the handy blocks of code that can organize your code into single-purposed sections to make programming easier. Subroutines did not return values, but you can pass values to subroutines in an argument l ist .Syntax is

Private/Public/Friend/Static sub procedure name {arg list}

Page 46: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 46

Statements

End sub

Arg list : - It is a l ist of arguments separated by commas. Each argument acts l ike a variable in the procedure. There are two types of sub procedures namely

General proceduresEvent procedures

The Publ ic keyword makes a procedure accessible to al l other procedures in al l modules and forms. The Private keyword makes a procedure accessible only to other procedure in the module or form in which it is declared. The Friend keyword is used only in class modules and specifies that the procedure is vis ible throughout the project, but not vis ib le to a control ler of an instance of an object . The Static keyword specifies that the procedure’s local variables should be preserved between cal ls. In argl ist you can include Optional, which means that an argument is not required, ByVal means that the argument passed by Value, ByRef means that the argument is passed by reference.

Event proceduresAn event procedure is a procedure that contains the control ’s actual name, underscore (_) and the event name.

E.g. : Pr ivate command1_cl ick()

End sub

General procedure:A general procedure is declared when several event procedures perform the same act ion. It is a good programming practice to write common statements in a general procedure and then cal l them in event procedures. In order to add a general procedure, the code window is opened for the module to which the procedure is added. Choose tools>add procedure. Type the name of the procedure in name box. Under type choose sub, function, property or event. Under scope publ ic is selected to create a procedure that can be invoked out side the module, or private to create a procedure that can be invoke from within the module.

You can also create new procedure by typing sub procedure name, function procedure name, property procedure name.

Procedure ScopeYou can restr ict the scope of procedures, and you do that with Private, Publ ic, Fr iend and Stat ic keywords. The Private and Publ ic keywords are the main keywords here; using them, you can specify i f a subroutine or function is private to the module or form in which it is declared or publ ic (that is global) to al l forms and modules. You use these keywords before the Sub or Function keywords l ike this

Private Function Return7()

Dim RetvalRetval=7Return7=Retval

End Function

You can also declare procedures as fr iend procedures with Fr iend keyword, which are usual ly used in c lassed modules to declare that the procedure is avai lable outside the class, but not outside the current project. this restr icts those functions being cal led i f the current project serves as an OLE automation server.

You can also declare procedures as Static , which means that the variables in the procedure do not change between procedure cal ls, and that can be very useful in cases l ike this, where we support a counter variable that is incremented each t ime a function is cal led:

Stat ic Function Counter()

Dim CounterValue as IntegerCountervalue=CounterValue+1Counter=CounterValue

End Function

Function proceduresFunctions are l ike sub procedures, except they return a value. They are useful for taking one or more piece of data cal led arguments. The function returns a value that indicates the results of task completed within the function. The Exit Function keyword cause an immediate exit from a Funct ion procedure. A Function is a block of code that you cal l and pass arguments to, and using functions helps break your code up into manageable parts.

SyntaxPrivate\Public\Friend\Static Function name (arglist) As Type

Page 47: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 47

StatementsEnd Function

E.g.: Function prod(a as double, b as double) as double.

Prod=a*b

End function

Property proceduresThis is used to create read only propert ies for forms, standard modules and class modules. VISUAL BASIC provides three kinds of property procedures.

Property let procedure : - that sets the value of the property

Property get procedure : - that returns the value of property

Property set procedure : - that sets the reference to an object

E.g. :-

Publ ic Property Let Company(Byval s Input as Str ing)

MvarCompany=sInput

End Property

Publ ic Property Get Company() As Str ing

Company=mvarCompany

End Property

ByVal Vs ByRef

When You create Procedures that take arguments, there are two possible ways to pass those arguments: by Value (ByVal) or reference (ByRef). ByVal means that VISUAL BASIC passes a copy of the variable to the procedure. This method does not al low the procedure to change the actual contents of the variable in the cal l ing procedure. By Default VISUAL BASIC passes arguments by reference. Passing arguments by value using ByVal is general ly faster than passing arguments by reference using ByRef. So i f your code does not need to change the data type, use ByVal for fastest results.The except ion to this rule occurs when passing large str ing or array arguments. Even i f the procedure wi l l not modify them, it ’s often faster to pass the argument ByRef than using ByVal. This is because ByRef passes a four-byte pointer to your data, not the actual data. I f you are passing a large character str ing or large array, i t ’s quicker to use ByRef instead of ByVal.

E.g. :-

Dim Arg As Str ing

Arg=”hank”Abc Arg ‘ Cal ls abc

IF Arg=”hank” ThenMsgBox”Same”

ElseMsgBox”Changed”

End I f

Sub Abc(ByVal Arg as Str ing)

Arg=”Nets”

End Sub

In this example, Arg variable would remain “hank” outside of Sub Abc, even though it was changed within the procedure. This is because ByVal keyword did not pass the actual variable Arg. I t passed a copy instead. On the other hand, by using ByRef (or leaving modifier), the change to Arg with Sub Abc would change the data outside of the procedure.

Page 48: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 48

Sending Keystrokes to Other ProgramsYou can use the SendKeys() function to send keys to the program that currently has the Windows focus, just as i f you types those keys yourself . Using the Alt key, you can reach the menu items in your spreadsheets Fi le menu.

Syntax

SendKeys str ing [ , wait]

The str ing expression is the str ing you want to send to other program. The wait argument is a Boolean value indicating the wait mode. I f False, control returns r ight after the keys are sent. I f True, the keywords must be processed by the other program before control returns. I f the keys you want to send are not s imple text, just embed the codes you see in the fol lowing table in the text you send to SendKeys( )

SendKeys( ) key codes

Key Code

BackSpace {BACKSPACE}, {BS}, OR {BKSP}Break {BREAK}Caps Lock {CAPSLOCK}Del or Delete {DELETE} OR {DEL}Down Arrow {DOWN}End {END}Enter or Return {ENTER} OR ~Esc {ESC}Help {HELP}Home {HOME}Ins or Insert {INSERT} OR {INS}Left Arrow {LEFT}Num Lock {NUMLOCK}Page Down {PGDN}Page Up {PGUP}Print Screen {PRTSC}Right Arrow {RIGHT}Scrol l Lock {SCROLLLOCK}Tab {TAB}Up Arrow {UP}F1-F16 {F1} – {F16}Shift +Ctrl ^Alt %

Ending a Program at any timeYou use END statement to stop execut ion of your program-but note that i t does so immediately, which means that no Unload() or s imilar event handl ing functions are cal led. End just brings the program to an end.

Control StructuresWhen designing a new appl icat ion the developer needs to execute sect ion of codes condit ional ly. The program should respond for condit ion or test i f the condit ion is true then the code wi l l be processed. Control statements are used to control the flow of program execution

VISUAL BASIC supports control structures such as

IF…THEN, IF… THEN…ELSE…END IF

SELECT…CASE…END SELECTVISUAL BASIC supports loop structures such as

FOR…NEXT

FOR EACH… NEXT

DO WHILE… LOOP

DO…LOOP WHILE

WITH.... END WITH:-

WHILE… WEND

IF…THEN…ELSE…END IFI t is used for condit ional execut ion of one or more statements.

Page 49: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 49

Syntax: IF <condit ion> THENSTATEMENTS

ELSESTATEMENTS

END IF

E.g. :- IF a>=10 THENK= 10

ELSEK=5

END IF

The statement is executed only i f the condit ion is true, otherwise the statement after ELSE part is executed.

SELECT CASE…CASE…END SELECTI t is an alternative of I f…Then…Else. This is more convenient to use than I f…Else…

End i f .

Syntax:- Eg:

Select Case Index Select Case aCase 0 Case 0Statements a=a*10Case 1 Case 1Statements a=a*20Case 2 Case 2Statements a=a*30End Select End Select Using Switch( ) and Choose( )The Switch( ) function evaluates a l ist of expressions and returns a variant value or an expression associated with the first expression in the l ist that is true.

Syntax

Switch (expr-1, value-1[, expr-1, value-2…[, expr-n, value-n]])

In this case expr-1 is the first expression to evaluate; i f true, Switch( ) returns value-1. I f expr-1 is not True but expr-2 is, Switch( ) returns value-2 and so on.

E.g. :Dim intValue

intValue=InputBox(“Enter a Number”)

intAbsValue=Switch(intvalue < 0, -1 * intvalue, intvalue > = 0, intvalue)

MsgBox “Absolute value” & Str( intAbsValue)

The Choose function returns one of a number of choices based on an index.

Syntax

Choose (index, choice-1 [, choice-2,…[, choice-n]])

I f the index value is 1, the first choice is returned, i f index equals 2, the second choice is returned, and so on.

ExampleDim int ID

intId=-1

While intID < 1 or intID >3

intID=InputBox(“Enter Employee ID”)

Wend

MsgBox “EmployeeName=” & Choose ( intID, “Bob”, “Denise”, “Ted”)

DO WHILE........LOOP :-I t is used to execute statements unti l a certain condit ion is met.

Syntax:-

Do While <Logical Expn>

Page 50: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 50

Statements to execute i f expression TrueLoop

E.g.:- the fol lowing Do Loop counts from 1 to 100

A=1Do whi le a<=100A=a+1Loop

DO .....LOOP WHILE:-The Do.. . loop whi le statement first executes the statement and then test the

condit ion after each execut ion.

Syntax

DoStatements to Execute

Loop While <Logical Expn>

A=1Doa=a+1Loop whi le a<=100

DO....LOOP UNTIL statement:-The Do.. . loop unti l structure executes the statement unt i l the condit ion is

satisfied. I t is an infinite loop.To get release from infinite loop press Ctr l+break.

Syntax:

Do

Statements

Loop Unti l <Logical Expn>

FOR...NEXT :-The For.. .Next. . .Loop is another way to make in VISUAL BASIC.

Syntax

For <counter>=<init ial Value> to <Maximum Value> | Step <Step Value>

Statements to Execute

Next <counter>

E.g.:-For I=1 to 100 step 1

StatementsNext

For I=0 to screen.fontcount-1Combo1.additem Screen.fonts(I)Next I

Exit for and exit loop : -A for . . .next loop can be terminated by an exit for statement.

E.g. :-For I=1 to 100Text1.text=str( I )I f I=50 thenExit forEnd i fNext.

A Do whi le loop can be terminated using exit Do statement.

FOR EACH… NEXT:-

The For Each… Next Loop performs a block of statements l ike For…Next loop, except that i t repeats a groups of statements for each element in a col lection of objects or an array rather than repeating the statements a specified number of t imes. This is very useful when you don’t know howmany elements are in a col lection or array. The loop starts with the first e lement in the array or col lection.

Page 51: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 51

E.g.:-

Dim MyArray(12) As Variant1) Dim Element As Variant

For Each Element in MyArray( )

MyArray(Element)=”Hel lo”

Next Element

2) Dim MyRs as RecordsetSet MyRs=MyDb.CreateRecordset(“Stock” )

For Each Field in MyRs

Combo1.AddItem MyRs.Field.Name

Next Fie ld

WITH.... END WITH:-When propert ies are set for objects or methods are cal led, a lot of coding is

included that acts on same object. I t is easier to read the code by implementing With ...End with statement. The code is executed more quickly and efficiently that the object is evaluated only once.

E.g. :-With text1.font.bold=true.font. i tal ic=true.text1=”Nets”End with

WHILE …WEND The While/Wend structure is structural ly identical to one variation of the Do/ Loop structure

Syntax: While <Logical Expn>

Statements

WendE.g.:-

While Not rs.EofPrint rs! Itemname

Wend

Page 52: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 52

Chapter 10

Arrays, DataTypes & FunctionsArrays:-

A sequence of variables by the same name can be referred using arrays. The individual element of an array is identified using an index. Arrays have upper and lower bounds. You can declare an array of any of basic data types and object variables. The individual elements of an array are same data type.

In VISUAL BASIC there are two types of arrays

1) Fixed size arrays : - i t can be declared by giving a name to array with upper l imit in parenthesis. The upper l imit should always be with in the range of long data type.

E.g. :-Dim myarray (10) as integerDim myarray (10)

The array declaration creates an array with 10 elements with index numbers running from 0 to 9. I f you want to specify the lower l imits then parenthesis should include both lower and upper l imit as fol lows.E.g. :-

Dim myarray (2 to 12) as integer

In the above statement an array of 10 elements is declared with indexes running from 2 to 12.

A publ ic array can be created using keyword publ ic instead of dim.E.g. :- Publ ic myarray(10) as integer

Publ ic myarray (10)Publ ic myarray (20 to 12)

Multi dimensional arrays:-I t is used when we need to alter related information of different dimension.E.g. :-

Dim myarray(10,10)Dim myarray (2 to 12,101 to 110)Any no. Of dimension can be declared in a mult i dimensional array.

2) Dynamic arrays: -There wi l l be situation were the user may not know the exact size of array at

design t ime. In such circumstances, a dynamic array can be init ial ly declared and can have elements when needed.E.g. :-

Dim myarray ()

The actual no. of element can be located using redim statement.

Redim myarray(10)Redim myarray(12)

The Redim statement can appear only in a procedure. Redim is a executable statement. The lower and upper l imits can also be specified as in a fixed size array.

E.g. : Redim myarray (2 to 12). Each t ime on executing the redim statement, the current data stored in a array is

lost and the default value is set. But i f you want to change the size of array without losing previous data use ‘preserve’ keyword with redim statement.

E.g. : Redim preserve my array (2-12) When the preserve keyword is used, only the upper l imit of the last dimension in

a mult id imensional array can be changed.

The Array( ) Function

You can also use the Array( ) function to create a new variant holding an array. Here’s how you use Array( )

Array (argl ist)

The argl ist argument is a l ist of values that are assigned to the elements of the array contained within the variant. Here’s an example that creates an array with the values 0, 1, and 2.

Dim A As VariantA=Array (0,1,2)

User defined data types:

Page 53: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 53

Variables of different data type when combined as a s ingle variable to hold several related information is cal led user defined data types.

A type statement is used to define a user defined type in the general declaration section of a form or module. User defined data type can also be private in a form while in a standard module it can be publ ic or private.

E.g. : Pr ivate type products prod_id as integer

H_name as str ingPrice as double

End type

The user defined data type can be declared with a variable using dim statement as in any other variable. An array also can be declared of user defined data type

dim ab as products

A user defined data can be referred in an appl ication by using the variable name. the procedure along with item.name in the type block.

E.g. : ab.H_name=”TV”Text1.text=ab.H_name

ConstantsConstants are named storage location in memory, the value of which does not change during program execution. The constant statement is used to create a constant. Constants can be declared in local , form module or g lobal scope and can be publ ic or private.E.g. : Publ ic constants Pie as s ingle=3.14

Built-in functionsVISUAL BASIC offers many bui lt- in functions under various categories.

Numeric Functions

Date & Time functionDate and t ime are internal ly stored as number in VISUAL BASIC and represent al l number posit ion with the date between 1st Jan 100 to 31st Dec 9999.

The system’s current date and t ime can be retr ieved by using now, t ime functions in VISUAL BASIC. Now() function retr ieves the date and t ime. Date() funct ion retr ieves only date, and t ime() only t ime.

String FunctionsAbs:- The Abs function returns the absolute values of a number. Abs returns the unsigned values of the suppl ied numeric expression.

SyntaxAbs(number)

E.g. :X=Abs(-5) 5

Asc, AscB, AscW : - The Asc funct ion returns the numeric code of a character. The range for returns is from 0 to 255. The AscB function is used with byte str ings. Instead of returning the character code for the first character, AscB returns the first byte. The AscW function returns the Unicode character code except on platforms where Unicode is not supported.

SyntaxAsc(str ing expression)

E.g. :X=Asc(“A”)Print A 65

BOF:- The BOF function returns the beginning of an open file status. This function is useful when for checking i f the cursor has reached beginning of a file. This function returns True i f the pointer is at beginning of file, else it returns False.

SyntaxFi lename.BOF

E.g.:-

IF rs.BOF=True Then

MsgBox “Beginning Of Fi le”End I f

CBool:- Cobol function converts a numeric or str ing expression to Boolean.

Page 54: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 54

SyntaxCobol(expression)

E.g. :X=Cobol(1) TrueX=Cobol(0) False

Cbyte:- Cbyte converts a numeric or str ing expression to Byte.

SyntaxCbyte(expression)

E.g. :X=Cbyte(25) 255 ‘ the number must be between 0 and 255.

Ccur:- Convert from a numeric or str ing expression to Currency.

SyntaxCcur(expression)

E.g. :X=Ccur(234444) 234444 ‘ the number must be in the range of

currency value.

Cdate:-Convert a numeric or str ing expression to Date

SyntaxCdate(expression)

E.g. :X=Cdate(“12/03/2001”) 12/03/2001 ‘ returns a date type data.

CDbl:- Convert a numeric or date to Double data type

SyntaxCDbl(expression)

E.g. :X=Cdbl(12322) 12322 ‘ the number must be in double data range.

Chr, ChrB,ChrW:- The Chr funct ion return the character that corresponds to the suppl ied ANSI code. Normally the ANSI code must be in the range of 0 to 255. This function is useful for specifying characters that you cannot type at the keyboard, such as special control codes for the printer. Another good use is to produce double quote marks in str ings. You can use Chr(34) to return double quote marks. The ChrB function is used with byte data contained in a str ing and always return a single byte. The ChrW function returns a str ing containing Unicode character.

SyntaxChr(ANSIcode)

E.g. :X=Chr(65)Print X A

Cdec:- Convert a numeric or str ing to Decimal data type.

SyntaxCdec(expression)

E.g. :X=Cdec(1233) 1233 the number must be in decimal range.

Cint:- Convert a numeric or str ing to integer data type.

SyntaxCint(expression)

E.g. :Cint(32155) 32155 the number must be in integer data range.

CLng:- Convert a numeric or str ing to long data type.

SyntaxClng(expression)

E.g. :Clng(1233) 1233 the number must be in long data range

CSng:- Convert a numeric or str ing to s ingle data type.

SyntaxCSng(expression)

E.g. :CSng(1233) 1233 the number must be in s ingle data range

CStr:- Convert a numeric or str ing to str ing data type.

SyntaxCStr(expression)

E.g. :

Page 55: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 55

CStr(1233) 1233

CurDir:- Returns the current default d irectory for the specified drive. This funct ion returns a variant type data. You can also use CurDir$ function to return a str ing type data.

SyntaxCurDir(drive$)

E.g. :X=CurDir(“C:”)Print X

Cvar:- Converts a str ing or numeric to variant data type.

SyntaxCvar(expression)

E.g. :Cvar(3444) 3444

Date, Date$:- Returns Current system date. Date function returns date data type and Date$ returns str ing type date.

SyntaxDate

E.g.:X=Date$Print X

DateSerial:- The DateSerial function converts the numeric values of an indicated date to a Visual Basic date data type. This funct ion returns a variant data that represents the month, day, and year of a date on the calendar.

SyntaxDateSeria l(year,month,day)

The year argument is a number between 100 and 9999, the month argument is a no. of month between 1 and 12, date argument stands for a val id number for date

between 1 and 31. E.g. :

Newdate=DateSerial(2001,12,25)Print NewDate

DateValue:- The DateValue function converts a date in the form of a str ing into a Visual Basic date data type. This function changes different ly formatted dates to a universal numerical form.

SyntaxDateValue(datestr ing)

E.g. :Dim dtfirst as dateDtfirst=DateValue(“25/12/2001”)Print dtFirst

Day:- returns an integer value representing day of given date.

SyntaxDay(dateexpression)

E.g. :Dy=Day(now())Print Dy

DISTINCTROW:- The DistinctRow funct ion filters dupl icate rows from a recordset.

SyntaxSelect DISTINCTROW field1, field2, field3… from Tablename

E.g.:Select DISTINCTROW Customer.Name From Customer INNER JOIN on _Customer.CustomerID=Order.CustomerID

Page 56: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 56

EOF:- The EOF function returns the end of file status of an open file. I t is important to check the end of file status to avoid reading past the end of file. This function returns a Boolean value True or False.

SyntaxFi lename.EOF

E.g.:IF rs.EOF Then

MsgBox “End of Fi le”

End I f

Exp:- This function raises the natural logarithmic base e (base about 2.718282) to the specified power.

SyntaxExp(number)

E.g. :X=Exp(1234)Print X 162754.791419004

FileLen:-The Fi leLen function returns the total length of a file in bytes. I t is useful to determine the size of a file. This function returns a long integer value.

SyntaxFi leLen(filename)

E.g. :X=Fi leLen(“C:\Windows\config.txt”)Print X

Fix:- The Fix function returns the whole-number portion of a dblexpression. Al l d igits to the r ight of decimal are trunctated. No rounding is performed.

SyntaxFix(dblexpression)

E.g. :X=Fix(5.34) 5

Format : - The Format funct ion takes a str ing, number, or date variant and returns a formatted number, date, or t ime. The Format parameter can have more than one part depending on the type of the item to be formatted. For numbers, you can have up to four parts. Part 1 is posit ive numbers, part 2 for negat ive numbers, part 3 for 0, and part 4 is for nul l . For str ings you can have two parts. The first part for str ings with one or more characters and the second part for zero length str ings (“ “) or Nul l .

Syntax

Format ( expression, “format1; format2”, firstdayofweek, firstweekofyear)

Here expression is the data to format, format specifies how to format the expression, firstdayofweek is an opt ional parameter used when formatt ing dates, firstweekofyear is another opt ional parameter when formatting dates. The formats avai lable are

Argument Description

(0) Displays a zero or a number(#) Displays a number or nothing(.) Decimal point. Actual decimal point is based on regional sett ings(%) Percentage. Number is mult ipl ied by 100 and percent s ign is shown based on

posit ion of % in format.( ,) Thousands separator. Actual separator depends on regional sett ings(:) Time separator. Actual separator depends on regional sett ings(/) Date separator. Actual separator depends on regional sett ings@ Character placeholder. Displays a character or space.& Character placeholder

Displays a character or nothing< Force lowercase> Force uppercase! Force left to r ight fil l of p laceholders(E-E+e-e+) Scientific notat ion-+$( ) Displays character entered(\) Displays next character, regardless of meaning within the formatted str ing

“General Number” No thousands separator“Currency” Use thousands separator and display two places to the r ight of decimal

places“Fixed” Display at least one number to the left of decimal place and two to the

r ight“Standard” Use thousands separator, one place to the left of decimal and two to

Page 57: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 57

the r ight.“Percent” mult ipl ies number by 100 with two places to the r ight of decimal place.“Scient ific” standard scientific notat ion“Yes/No” Displays Yes unless the number is 0; then it displays No“True/False” Displays False unless the number is 0; then it displays True“On/Off” Displays On unless the number is 0; then it displays Off

E.g.:

ab=1000Bc=format(ab,”0.00”)1000.00

ab=now()bc=format(ab,”DD/MM/YY”)

Examples

Sformat=”Currency”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Sformat=”######.00”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Sformat=”000000.##”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Sformat=”Standard”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Sformat=”General Number”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Sformat=”Fixed”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Sformat=”Percent”Picture1.Print Sformat & “: “; Tab(30); Format( Val(Text1), Sformat)

Examples using Format$ to display date and t ime

Format$(Now,”m-d-yy”) - “1-1-00”Format$(Now,”m/d/yy”) - “1/1/00”Format$(Now,”mm-dd-yy”) - “01-01-00”Format$(Now,”ddd,mmmm d,yyy”) - “”Friday,January 1, 2000”Format$(Now,”d mmm,yyy”) - “1 Jan,2000”Format$(Now,”hh:mm:ss mm/dd/yy”) - “01:00:00 01/01/00”Format$(Now,”hh:mm:ss AM/PM mm-dd-yy”)

“01:00:00 AM 01-01-00”

Hex:- The Hex function converts a decimal numeric expression to a variant or str ing that represents the value of the numeric expression in hexadecimal format.

SyntaxHex(numexpression)

E.g. :X=Hex(1234.55)Print X 4D3

Hour:-The Hour function returns an integer representing the hour of given t ime.

SyntaxHour(t ime expression)

E.g. :X=Hour(Now())Print X

IN:- The IN funct ion checks to see i f a value is a member of subquery’s results. The optional NOT checks i f a value is not a member of a subquery’s results.

SyntaxQueryexpression [NOT] IN (subquery)

E.g. :Select Name from Customers where CustomerID NOT IN(Select CustomerID From Products)

Input, Input$:- Reads a str ing of characters from a file, assigning no special meaning to carr iage returns and l ine feeds.

Page 58: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 58

SyntaxInput$(input length,filenumber)

E.g. :Input$(100,1) ‘ reads 100 characters from the file opened as number 1.

InputBox:- This function displays a d ialog box with a message and a text box in which user can enter some text

SyntaxInputBox(Prompt[, Ti l te][,defaulttext][, left ,top][,helpfile,context])

E.g. :Ss=InputBox(“Enter your name”,Entry Box”)Print ss

Instr:- This function return the posit ion of an occurrence of a search str ing within another str ing being serached. I f the str ing is not found Instr funct ion returns 0.

SyntaxInstr([startpo],str ing1,str ing2)

The parameter str ing1 is the str ing that wi l l be searched. Str ing2 is the str ing that is being searched for. I f str ing2 is found within str ing1, the Instr returns the posit ion where the str ing is found. You can use the optional startposit ion parameter to specify the search to start for.

E.g. :X=Instr(“ICES”,”C”) 2

Int:- The Int Funct ion returns the largest integer that is less than or equal to the suppl ied numeric expression. I t essent ial ly rounds a numeric expression to the nearest integer.

SyntaxInt(numeric expn)

E.g. :X=Int(5.44) 5

Return values for Fix, Int and Cint functions

Value Fix Int Cint

2.7 2 2 32.2 2 2 22 2 2 2-2 -2 -2 -2-2.2 -2 -3 -2-2.7 -2 -3 -3

Lcase() : Converts given str ing to lower case.

SyntaxTextdescription=Lcase(str ing expression)

E.g. :

X=”ICES”Y=Lcase(X) ices

Left:- The Left function return a portion of a variant or a str ing, start ing at the first character from the left s ide of the str ing given. The str ing argument specifies the str ing and the intlength parameter specifies the number of characters to copy.

SyntaxLeft(str ing,intlength)

E.g. :X=Left(“ICES”,2) IC

Len:- The Len function return the storage length of a variable. They are most commonly used to find the length of a str ing.

SyntaxLen(str ingepression)

E.g. :X=Len(“Indian Computer”) 14

Page 59: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 59

LoadPicture:- The LoadPicture function places pictures in forms, image controls and picture boxes. The loaded picture must be in bitmap (.BMP), device independent bitmap(DIB), icon ( ICO), run- length encoded (RLE), Windows Meta Fi le (WMF), Windows Extended Metafile (EMF), Graphical Interchange Format (GIF), or Joint Photographic Experts Group ( JPG) format. Use LoadPicture funct ion without file name to c lear the contents of the object

SyntaxLoadPicture(Fi lename)

E.g. :Image1.Picture=LoadPicture(“C:\WINDOWS\CLOUDS.GIF”)

Loc:- The Loc function returns the current posit ion of the pointer for an open file, which indicates where the next read or write operation wi l l occur. The meaning of the number returned depends on the mode under which the file was opened.

SyntaxLoc(filename)

E.g. :X=Loc(1) this example places a number represent ing the current posit ion in the

file

LOF:- The LOF file returns the length in bytes of an open file.

SyntaxLOF(filenumber)

E.g. :LOF(1)

Log:- The Log funct ion returns the natural logarithm of a numeric expression. The natural logarithm, which has a base of approximately 2.718282.

SyntaxLog(dblexpression)

E.g. :Log(12.34) 2.51284601847724

Lset:- The Lset function moves data from str ing or user define type (UDT) to another. When Lset is used to move data from one variable to another, the data in the from variable is placed left justified in to the variable.

SyntaxLset s1=s2

E.g.:X=”ICES”Y=”COMPUTER”Lset X=YPrint X COMP

Ltrim:- The Ltr im function returns a copy of a str ing with any leading spaces removed. The Str ing parameter specifies the str ing.

SyntaxLtr im(str ing)

E.g. :X=Ltrim(“ ICES”) “ICES”

Max, Min:- The Max Function is used to return the highest value in a given field, and the Min function is used to return the lowest value in a given field.

SyntaxMax|Min (expression) as resultfield

E.g. :Select Max(Qty) As MXQty From StockSelect Min(Qty) As MNQty From Stock

Mid:-The Mid funct ion returns the specified port ion of a str ing expression. This function returns the specified substr ing of a str ing expression. The strexpression parameter designates the source str ing and can be a fixed or variable length str ing, a str ing constant, a l i teral str ing, the result of any funct ion that returns a str ing, or a variant that can evaluate to a str ing. The intstart parameter specifies the posit ion within the source str ing where the copy wi l l begin. The intlength parameter is used to specify how many characters wi l l be copied. This is an optional parameter. I f not used, the function wi l l return al l the characters from intstart posit ion to end of str ing.

SyntaxMid(strexpression,intstart, int length)

E.g. :X=Mid(“ICES”,2,2) CE

Page 60: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 60

Minute:- The Minute funct ion returns an integer representing the Minute of given t ime.

SyntaxMinute(t ime expression)

E.g. :X=Minute(Now())Print X

Month:- returns an integer value representing Month of given date.

SyntaxMonth(dateexpression)

E.g. :Dy=Month(now())Print Dy

MsgBox:-The MsgBox funct ion displays a dialog box with a message and an optional icon. Your program instructs the function to display one or more sets of predefined command buttons on the dialog box. When the user select one of these buttons, this function returns a number based on the selected button.

SyntaxMsgBox(Message$[,Options][ ,Boxname][ ,HelpFi le,context])

E.g. :Result=MsgBox(“Are You Sure to Delete”,vbCrit ical+vbYesNo,”Delete”)

Now:-The Now Function provides the current date and t ime of the computer’s system clock-calendar as a date data type.

SyntaxNow()

E.g. :X=Now()Print X

Nper:- The Nper funct ion calculates the number of periods for an annuity, assuming constant payments and interest rate.

SyntaxNper(Rate,Payment,Start ing Value)

E.g. :X=Nper(1.5/100,-2500,10000)Print X 61

Note: Either Payment or Start ing value must be given in negative value.

Oct:- The Oct function returns a variant or str ing that represents the suppl ied numeric expression in octal notation (base 8)

SyntaxOct(numexpression)

E.g. :X=Oct(1234.55)Print X 2323

Pmt:- Use the PMT function to return the total payment amount (Principal and interest) on an annuity, assuming constant periodic payments and a constant interest rate.

SyntaxPMT(Rate,No. of payments,Present value)

E.g. :X=PMT(1.5/100,60,-100000)Print X 2539.34274271092

PV:- Use the PV function to derive the present value of an annuity, assuming a constant stream of periodic and an unvarying interest rate.

SyntaxPV(Rate,no.of payments,Payment)

E.g. :X=PV(1.5/100,60, -2539.34274271092)Print X 100000

Page 61: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 61

QBColor:- The QBColor function helps define the color of an object on the screen. An object defined with this funct ion is one of 16 possible colors. These colors s imulate the 16 standard colors of older DOS based programming languages.

It has fol lowing values

QBColor number Color

0 Black1 Blue2 Green3 Cyan4 Red5 Magenta6 Yel low7 White (Light Gray)8 Gray9 Light Blue10 Light Green11 Light Cyan12 Light Red13 Light Magenta14 Light Yel low15 Bright White

SyntaxQBColor(color number)

E.g. :Text1.BackColor=QBColor(10)

Rate:- The Rate funct ion returns the interest of an annuity, given a constant periodic series of cash payments and an unvarying interest rate.

SyntaxRate(no.of payments,payment,present value)

E.g. :Rate(60, -2539.34274271092,100000)Print X 1.5

RGB:- The RGB function provides a means of defining the color of an object on the screen. Each value in RGB funct ion expression represents the amount of red, green, and blue contained in the displayed color. The fol lowing l ists some common colors with the corresponding Red, Green and Blue arguments.

Color Red Value Green Value Blue Value

Black 0 0 0Red 255 0 0Green 0 255 0Yel low 0 255 255Blue 0 0 255Magenta 255 0 255Cyan 0 255 255White 255 255 255Light Gray 192 192 192Dark Gray 128 128 128

SyntaxRGB(redvalue,greenvalue,bluevalue)

E.g. :Text1.BackColor=RGB(150,200,100)

Right:- The Right Function returns a portion of a str ing, start ing at the last character working to the left , for the length specified. The strexpn parameter is used to specify the str ing and intlength parameter specifies no. of characters to copy from the r ight s ide.

SyntaxRight(strexpn,int length)

E.g. :X=Right(“ICES”,2) ES

Rnd:- The Rnd function returns a s ingle-precis ion random number between 0 and 1.

SyntaxRnd(Number)

E.g. :Text1.backcolor=rgb(rnd*255,rnd*255,rnd*255) ‘ wi l l change the back color

cont inuously.

Page 62: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 62

Rtrim:- The Rtr im function returns a copy of a str ing with any tra i l ing spaces removed. The strexpn specifies the str ing

SyntaxRtrim(strexpn)

E.g. :X=Rtrim(“ICES “) “ICES”

Second:- The Second funct ion returns an integer representing the Second of given t ime.

SyntaxSecond(time expression)

E.g. :X=Second(Now())Print X

Sgn:- The Sgn function evaluates a numeric expression and returns a value based on whether the number expression is negative, posit ive or 0. I t returns 1 i f number is posit ive, -1 i f number is negat ive and 0 i f number is zero

SyntaxSgn(numericexpression)

E.g. :X=Sgn(-100)Print X -1

Shell:- The Shel l function runs a specified .EXE, .COM, .BAT or .P IF program. The optional mode argument specifies the window mode and has fo l lowing values

Constant Number Description

VbHide 0 Window is hidden with focusVbNormalFocus 1 window has focus and restored to normal s izeVbMinimizedFocus 2 window is minimized with focusVbMaximizedFocus 3 window is maximized with focusVbNormalNoFocus 4 window is restored to i ts or iginal s ize and posit ion

without focusvbMinimizedNoFocus 6 Window is minimized without Focus

SyntaxShel l(Program name[,mode])

E.g. :w = Shel l("C:\Windows\Calc.exe", 3)

Space:-The space function returns a str ing containing the specified number of spaces. The intlength specifies the no. of b lank spaces.

SyntaxSpace(intlength)

E.g. :X=Space(5) “ “

Spc:- The Spc function skips a specified number of spaces in the Print method.

SyntaxSpc(number)

E.g. :Pr int Spc(10); “Ten spaces in, and now”; Spc(Int(Rnd*20));”random!”

Sqr:- Returns the square root of a number.

SyntaxSqr(number)

E.g. :X=Sqr(36) 6

Str:- The Str funct ion converts numeric data into an unformatted str ing.

SyntaxStr(number)

E.g. :X=Str(1234)Print X “1234”

Page 63: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 63

StrComp:-The strComp compares two str ings and returns one of four values based on result as fol lows

Condition Value

String1 < str ing2 -1Str ing1 = str ing2 0String1 > str ing2 1Either str ing is nul l Nul l

SyntaxStrComp(str ing1,str ing2[,comparetype])

You can use the optional comparetype as 0 for case sensit ive and 1 for case insensit ive

E.g. :X=StrComp(“hel lo”,”hal lo”) 1

StrConv:-StrConv converts a str ing into the specified format. The strexpn specifies the str ing and conversion type specifies the type of conversion using vb constants. The different constants are

Constant Value Description

VbUppercase 1 Converts to uppercaseVbLowercase 2 Converts to lowercaseVbPropercase 3 converts first character of each word to uppercase

SyntaxStrConv(strexpn,convtype)

E.g. :X=StrConv(“indian computers”,vbPropercase) Indian Computer

String:- The Str ing function returns a str ing containing the specified number of the requested character. Lengthnumcharacters specifies the number of character and intcharacter specifies the character.

SyntaxStr ing(lengthnumcharacters, intANSICode)Str ing(lengthnumcharacters, intcharacters)

E.g. :X=Strin(15,”@”) @@@@@@@@@@@@@@@

Sum:- The Sum function is used to return the sum of al l the values in a particular field of a recordset.

SyntaxSum(expression) As resultfield

E.g. :Select Sum(Qty) As Sqty From Stock

Tab:- Use the Tab funct ion to move to a particular character posit ion on the current l ine of form or printer object.

SyntaxTab(column)

E.g. :For J= 1 to 20

Print Tab(j) ; “Test”; Tab(60-2*j); “Case”Next

Time, Time$:- The Time function returns the current system time as a date data type. The Time$ function returns your computers current system time as Str ing.

SyntaxTime

E.g.: X=Time$Print X

Page 64: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 64

Timer:- The Timer Function provides the number of seconds that have elapsed since 12:00 midnight. This funct ion may serve as a reference for determining the number of seconds elapsed between two different uses of the Timer function on the same day.

SyntaxTimer

E.g. :Pr ivate Sub Timer1_Timer( )

Stat ic St as doubleDim msg as str ingDim elp as long

Timer1. interval=500Elp=int(t imer)

If st =0 ThenSt=elp

End I fText1.Text=Str(elp) & “ elapsed seconds since midnight”Text2.Text=Str(elp-st) & “seconds since program started”

End Sub

TimeSerial:- The TimeSerial function converts the value of an indicated t ime to a VISUAL BASIC date data type.

SyntaxTimeSerial(hour,minute,second)

E.g. :X=TimeSeria l(11,33,23)Print X 11:33:23

TimeValue:- The TimeValue function converts a t ime in the form of a str ing into a VISUAL BASIC date data type.

SyntaxTimeValue(timestr ing$)

E.g. :X=TimeValue(“11:55:40”)Print X 11:55:40

Trim:- The Trim function removes leading and tra i l ing spaces from a str ing. This is a combinat ion of Ltr im and Rtr im funct ions. Str ing argument specifies a val id str ing.

SyntaxTrim(str ing)

E.g. :X=Trim(“ ICES “) “ICES”

Ucase:-The Ucase function returns a copy of a str ing in which al l lowercase alphabetic characters have been converted to uppercase. The strExpn specifies the str ing.

SyntaxUcase(strExpn)

E.g. :X=Ucase(“ices”) ICES

Val:- The Val function returns the numeric value of the suppl ied str ing expression.

SyntaxVal(str ingexpression)

E.g. :X=Val(“1234”)Print X

WeekDay:- returns an integer value representing Weekday of given date. You can optional ly include firstday of week as vbSunday, vbMonday, vbTuesday etc.

SyntaxWeekDay(dateexpression[,firstday of week])

E.g. :Dy=WeekDay(now())Print Dy

Year:- returns an integer value represent ing year of given date.

Syntaxyear(dateexpression)

E.g. :Dy=year(now())Print Dy

Page 65: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 65

Chapter 11

Clipboard, Control ArrayWorking with clipboard : - Cl ipboard is a common area for windows appl ications. The contents you have copied or moved (Using commands copy and cut) are placed at Cl ipboard. When you choose paste command, the contents of the c l ipboard is inserted at your cursor posit ion. The c l ipboard contents are updated when you cut or copy new items.The Cl ipboard is the simplest way to share data between programs. The Cl ipboard can hold three type of i tems. First, I t can hold text. Text is any combination of letters, numbers, or characters represented by ASCI I codes. Second, I t can hold graphics. Windows lets the user cut and paste pictures as wel l as text. However, unl ike the case with cutt ing, copying and past ing text, each individual program must define how graphics are to be handled. Final ly, the Cl ipboard can hold DDE (Dynamic Data Exchange) messages being sent from one program to another and l ink information for an OLE (Object Linking Embedding) object.The Cl ipboard is a temporary storage location, and may hold only one item attr ibute a t ime of each of these data types. When a program copies an item to the Cl ipboard, i t replaces any item of the same type that previously resided there. Anything on the cl ipboard disappears when you exit Windows, although you can use Cl ipboard Viewer program to view and save the contents to a file.

In VISUAL BASIC the Cl ipboard object is bui lt in and supports the fol lowing methods

Method Description

Clear Clear the contents of the Cl ipboard areaGetData Retrieve graphic data from the Cl ipboard areaGetFormat Return True i f the specified data type is stored in the cl ipboard areaGetText Retr ieve text from cl ipboard aresSetData Place graphic data on the Cl ipboard areaSetText Place text on the Cl ipboard ares

VISUAL BASIC constants for Clipboard object

Value constant Meaning

&HFFFFBF00 vbCFLink cl ipboard holds DDE l ink&HFFFFBF01 vbCFRTF cl ipboard holds Rich Text Format Fi le1 vbCFText cl ipboard holds text2 vbCFBitmap cl ipboard holds a bitmap graphic3 vbCFMetafile cl ipboard holds Windows Metafile Graphic8 vbCFDIB cl ipboard holds Device Independent bitmap9 vbCFPalette cl ipboard holds a color palette14 vbCFEMetafile cl ipboard holds enhanced Windows Metafile15 vbCFFi les cl ipboard holds a MS Windows Explorer filel ist

Syntax for different Methods that affect Cl ipboard

Clear : Clears the contents of cl ipboardSyntax

Cl ipboard.ClearE.g. :Pr ivate Sub cmdClearAl l_Cl ick

Cl ipboard.ClearEnd Sub

GetData : This method is used to retr ieve data from cl ipboard to an object

SyntaxCl ipboard.GetData([Format])

You can use the format argument as 0 or not specified- automatical ly use the correct format (default) , 2-vbCFBitmap requesting a bitmap graphic, 3-vbCFMetaFi le requesting a metafile graphic, 8-vbCFDIB requesting a device independent b itmap graphic, 14-vbCFEMetafile request ing an enhanced metafile graphic.

E.g. :Pr ivate Sub cmdData_Cl ick

Picture1.Picture=Clipboard.GetData(vbCFBitmap)End Sub

GetFormat : This method returns True i f the specified format is found.

SyntaxCl ipboard.GetFormat(format)

The different value for format argument is &HFFFFBF00-vbCFLink, &HFFFFBF01-vbCFRTF, 1-vbCFText, 2-vbCFBitmap, 3-vbCFMetafile, 8-vbCFDIB, 9-vbCFPalette, 14-vbCFEMetafile, 15-vbCFFi les

Page 66: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 66

E.g.:Pr ivate Sub cmdFormat_Cl ick

If Cl ipboard.GetFormat (vbCFText)=True ThenText1.Text=Clipboard.GetText

End I f

End Sub

GetText : Retr ieves text information from the c l ipboard.Syntax

Cl ipboard.GetText([format])

The format argument can be &HFFFFB00-vbCFLink, &HFFFFBF01-vbCFRTF, 1-vbCFText

Private Sub cmdtext_Cl ickText1.Text=Clipboard.GetText(vbCFText)

End Sub

SetData : P laces graphic information in the Cl ipboard object.

SyntaxCl ipboard.SetData graphic [ , format]

Graphic argument is an integer number that is the handle of the graphic image.Format argument can be 0 or notspecified-automatical ly determine correct format, 2-vbCFBitmap, 3-vbCFMetafile, 8-vbCFDIB, 9-vbCFPalette, 14-vbCFEMetafile

E.g. :Pr ivate Sub Cmd_Click()

Cl ipboard.SetData Picture1.Picture,vbCFBitmapEnd Sub

SetText : P laces text information in the Cl ipboard object

SyntaxCl ipboard.SetText Text[, format]

Text agument is any str ing information containing the text to send to cl ipboardFormat argument can be &HFFFFBF00-vbCFLink, &HFFFFBF01-vbCFRTF, 1-vbCFText

E.g. :Pr ivate Sub cmdCut_Cl ick

Cl ipboard.SetText Text1.SeltextText1.Seltext=””

End Sub

Control array : -A control array is a group of controls that share the same name and type. They also share the same event procedures. There are three ways to create a control array at design t ime.

a) Assigning the same name to the name property for more than one control .b) Copying an exist ing control and then pasting it on the formc) Setting the index property

The Index argument is only used i f the control is a part of a control array. This index specifies which element of the array is the one that activated the event. When referencing the control , the element being referenced must be specified by placing the index number between parentheses just after the control name, and before the property name for example Text1(0).TextControl arrays have just one event procedure for the entire array. This makes it easy to write generic code that appl ies to related controls that are grouped in the aray. Event procedures in control arrays always have an index argument that determines which control in the array tr iggered the event.E.g. : Pr ivate Sub Command1_Cl ick(Index As Integer)

Select Case IndexCase 0Text1.Text=Val(text1.Text)+0Case 1Text1.Text=Val(text1.Text)+1Case 2Text1.Text=Val(text1.Text)+2Case 3Text1.Text=Val(text1.Text)+3Case 4Text1.Text=Val(text1.Text)+4Case 5Text1.Text=Val(text1.Text)+5

End SelectEnd Sub

Page 67: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 67

Chapter 12

MDI Forms, Menus, Dialog BoxesMDI Forms:-Many VISUAL BASIC programs are nothing more than a str ing of windows, each of which causes the next to be displayed. In such case, often the programmer gives no thought whether the user can see more than one window at a t ime. each form may have its own menus, toolbars and other controls, al l of which take resources to display and t ime to code and manage. The Mult iple Document Interface (MDI) was original ly designed for appl ication such as MS WORD and MS EXCEL, which are designed to show more than one document simultaneously. This chapter shows you how principles developed for tradit ional MDI appl ications such as MS WORD and EXCEL can be used in your appl ications.

In VISUAL BASIC, the central window that contain other windows is treated as MDI form (Mult iple Document Interface) . Most MDI windows have menubars, toolbars, statusbar etc.

The MDI form is designed to maintain other forms with in i ts area.

VISUAL BASIC doesn’t use any MDI form by default, so i f you want one, you can add it to your project by selecting Project> Add MDI Form

Building the MDI form

Start a New standard EXE project Click alternate mouse button (r ight c l ick) in the project explorer window. Choose

Add > MDIForm. Pick MDIForm from under NEW and Cl ick Open

VISUAL BASIC restr icts you a single MDI form for your entire appl icat ion.When you have an MDI form in your appl ication, the other regular forms in the appl ication can be off two different types.

a) Standard Forms, which wi l l operate outside the MDI Form area. Opt ions, dialogs, and other modal windows should remain standard forms.

b) MDI chi ld Forms, which remain within the MDI form area. The user should be able to switch between chi ld forms without having to close one and open a new one. In addit ion, you may need to support having more than one copy of a particular type of form open at once. An MDIchi ld form should always be shown non modal ly. Whenever you want to show an MDI chi ld form, you should use code such as fol lowing

FrmMDIChi ld.Show

To set the form as MDI chi ld, choose Form> properties and set MDIChi ld property to True.

You cannot draw a control such as Textbox, Command Button etc. directly on MDI forms. You should use Picture Box control first and then draw the controls on it .

Menus:-Most Windows Appl ications have a menu structure. A menu al lows the user to access a number of different functions of the program. Typical menu systems have at least two levels. The top- level displays on the menu bar, and the second level d isplays as a drop down menu. Each form may have its own unique menu structure. Some menus have submenus branching off the second level; these al low further refinement of the actions avai lable to the user. VISUAL BASIC al lows up to four levels of submenus. VISUAL BASIC appl ications can be enhanced by adding menus. It offers a convenient and consistent way the group command and an easy way for users to access them.

Using the menu editor: -

A menu editor can use to create new menus modify exist ing menus etc.To create a menu control system for your form, select the form and choose tools>menu editor.

A menu editor window appears, Enter the first menu's Caption and Name, Cl ick the Next Button or press Enter. Cl ick the r ight arrow to indent one level, making this next entry a menu item. Enter the new items Capt ion and Name property. Repeat these steps for other menu items. Cl ick OK to c lose the menu editor. To add access Character use ampersand (&) before the Character in Caption property.E.g. :

&Fi le…New…Open&Edit…Cut…Copy…Paste

Page 68: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 68

To enter a command for the menu items, cl ick the menu item under design mode, this wi l l br ing the only cl ick event of the menu item. Type the command in the menu item's cl ick event.

E.g. : Pr ivate Sub mnuOpen_Cl ick( )Form1.Show

End Sub

Caption:- Caption indicates the text that appears on the menu. P lace an ampersant in front of one of the caption’s letters, indicating an accelerator key. Entering a hyphen (-) in the Caption text box places a separator bar in that menu posit ion.

Name:- Name refers to the Name property of the menu item, and serves as the name used in your code.

Index:- Use Index i f you want to create a control array for the menu. You would use this i f more than one menu item has the same name.

Checked, Enabled, and Visible: - Checked, Enabled, and Visible define the default state of the menu item you’re creating. A checked menu opt ion has a checkmark placed in front of i t to indicate its on/off state. Use the checked property to turn the check on and off in your appl ications code.

Negotiate posit ion:- Use Negotiate posit ion with OLE objects to determine the placement of your program’s menu items and an embedded OLE object’s menus.

Window List :- Window List creates an automatic l ist of al l open MDI chi ld windows.

Shortcut:- Shortcut defines a shortcut key associated with this menu entry, and HelpContextID lets you associate the entry with context-sensit ive help.

The actual structure of the menu shows as indentation levels in the bottom window. No indentation is a top-level menu that displays on the t i t le bar, each further indentation indicates one deeper level of submenu. You can easi ly control the level indentation by highl ighting the menu item and cl icking on the arrows immediately above Menu Editor' ’ main window.

Use Insert and Delete buttons to insert or remove a menu item.

Adding a Checkmark to Menu Item

Displaying a checkmark gives v isual feedback to the user about the toggle state of the option, and there’s two ways to add checkmarks to menu items: at design t ime and runtime.To add checkmark at design t ime to a menu item, you simply select the checked box in the Menu Editor.You can also set checkmarks at runt ime using a menu item’s Checked property. For example,

Pr ivate sub mnuEditInsert_Cl ick()Stat ic bb as Booleanbb=Not bbmnuEdit Insert.Checked=bb

End Sub

Adding a List of Open Windows to an MDI Form’s Window Menu

You can set a menu’s WindowList property to True to add a l ist of windows to that menu and you can set the WindowList property in the Menu Editor s imply by selecting a checkbox. Now, when the program runs, the menu you added a window l ist to wi l l indeed display a l ist of open windows, seperated from the rest of the menu items.

Creating and Displaying Popup Menus

Popup menus are displayed when you cl ick the alternate mouse button (normally r ight mouse button) on a form. To create a new popup menu, just use the Menu Editor, create a menu and make its Vis ib le property to False. Double c l ick the form now to open code window. The left dropdown box in code window l ists a l l objects in the form, so find you menu name and add code in i ts Cl ick event handlers.To display the popup menu, add a MouseDown event handler to your program using code window. Specify the which mouse button went down by comparing the Button argument to these predefined Visual Basic Constants VbLeftButton, VbRightButton, or VbMiddleButton. Then we use the Popupmenu method to d isplay the popup menu.

Eg:Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y

As Single)

If Button=vbRightButton ThenPopupMenu Popup

End I f

Page 69: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 69

End Sub

Dialogue boxes:-Dialog Boxes appear in almost every windows program. A dialog box is a special ized form meant to display or obtain specific information, and is hidden from sight once it has done its work. Some dia log boxes as extremely simple, displaying just a s ingle l ine of text whi le the program is performing a lengthy action. Other d ialog boxes may be complex, with many controls displaying a variety of information for the user to v iew or edit . VISUAL BASIC suppl ies several kinds of predefined dialog boxes. These make your programming job easier, because one l ine of code can cal l up a completed box to display a message or sol icit input. There are five basic sty les of dialog boxes. VISUAL BASIC provides four styles of predefined dialog boxes. You can these with just a few l ines of code to perform most basic interactions. The fifth style is a custom dialog box you bui ld yourself . I t can be as complex as you l ike.

MsgBox Statement : -The first style is the simplest message box. This type of dialog box simply d isplays a message and waits for the user to c lose the box by cl icking a button. The simple message dialog box is used to noti fy the user of certa in information. You can use a simple message box when you need to tel l the user what has happened, but don’t require anything from the user other than the acknowledgement impl ied in cl icking on the OK button.

SyntaxMsgBox Message [, options, BoxName, Helpfile, Context]

E.g. :Msgbox “Hel lo”, vbExclamation

MsgBox Function : - The second style of d ialog box also displays a s imple message. However, more than one command button is displayed on the dialog box so the user can choose among several options. In most windows programs, i f you attempt to exit a program with unsaved files, this type of dialog box appears and asks i f you want to save the files before exit ing. General ly , such dialog box wi l l have Yes, No and Cancel buttons. How the program acts when the dialog box c loses is based on the button you choose. The MsgBox Funct ion displays a dia log box with a message and an optional icon. Your program instructs the funct ion to display one or more sets of predefined buttons on the dialog box. When the user selects one of these buttons, this funct ion returns a number based on the selected button.

SyntaxMsgBox(Message[, Opt ions][, BoxName][, Helpfile, Context])

The Message argument is a str ing message to the user. Options argument is an integer value specifying which icon and button set wi l l be used with the dialog box. BoxName argument is a str ing expression that wi l l be used for the t i t le of the dialog box. Helpfile specifies the name of the helpfile for the dia log box. Context is the context number of the appropriate topic in the help file.

E.g. : Res=MsgBox(“Do You want to Exit”, vbYesNo+vbcrit ical , “Exit Project”)

Here you can use the variable res to determine which button was pressed.Values for the buttons displayed with MsgBox Function and Statement

Button Value vbconstants Meaning

0 vbOKOnly Display an OK button only (Default)1 vbOKCancel Display OK and Cancel buttons2 vbAbortRetryIgnore Display Abort, Retry, and Ignore buttons3 vbYesNoCancel Display Yes, No, and Cancel buttons4 vbYesNo Display Yes and No Buttons5 vbRetryCancel Display Retry and Cancel Buttons4000 vbMsgBoxHelpButton Adds a help button to the other displayed buttons

Values for the default button setting with MsgBox function and statement

Default Value vbconstants Meaning

0 vbDefaultButton1 (Default) Sets first button as default256 vbDefaultButton2 Sets second button as default512 vbDefaultButton3 Sets third button as default768 vbDefaultButton4 Sets fourth button as default

Values for icons displayed with MsgBox Function and statement

Icon Value vbconstants Used for

16 vbCrit ical Crit ical Messages32 vbQuest ion Queries48 vbExclamation Warnings64 vbInformation Information messages

Page 70: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 70

Values for the behavior of the MsgBox function and statement

Behavior Value vbconstant Behavior

0 vbAppl icationModal Prevents the user from interacting with the current appl ication unt i l the message box is completed.

4096 vbSystemModal Prevents the user from interacting with any appl ication unt i l the message box is completed.

10000 vbMsgBoxSetForeground Brings the appl ication to foreground i f i t is not the appl ication in focus

Values for the appearance of the MsgBox function and statement

Appearance Value vbconstants Appearance

80000 vbMsgBoxRight Right- justifies the text in the Message$ parameter

100000 vbMsgBoxRtlReading Displays the text r ight to left on Hebrew and

Arabic systemsValues returned by MsgBox function

Return Value vbConstants Button That was pressed

1 vbOK OK2 vbCancel Cancel3 vbAbort Abort4 vbRetry Retry5 vbIgnore Ignore6 vbYes Yes7 vbNo No

E.g.: 1) Private sub c_oncl ick

Res=Msgbox(“do you want to save”, vbyesno,”nets”)If res=vb yes then

Text1.text= “you cl icked Yes”End i f

End sub

2) Msgbox(“do you want +chr(13)+chr(10) to save”)

3) Trd= msgbox (“Do you want to save”,vbyesno+ vbcrit ical , “nets”)

Input box:-The input box function displays a modal d ialogue box that asks the user to enter some data. The dialogue box contains a message and an OK button and cancel button. The user can type in the text box and cl ick ‘OK’ or ‘Cancel’ to c lose the dialogue box. The InputBox is an alternative to designing a form with a text box for s imple text input.

Syntax:InputBox(Prompt [, Tit le][, DefaultText][, Left, Top])

The Prompt argument may be any str ing expression of upto 255 characters approximately to give instruction to the user, Tit le argument is for input box t it le, Default text automatical ly p laces the specified text in the box, Left and Top arguments specifies the posit ion of InputBox on the Screen

E.g.: res=input box (“Enter your name” ,” Input Name”,”ICES”)Text1.text=res

While the dialog box is displayed, the user can type a text in the textbox. When the user cl icks OK button, the dialog box wi l l disappear and return the str ing in the textbox. Optional ly the user can c l ick Cancel button. This also makes the dialog box disappear, but the str ing returned is nul l .

Page 71: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 71

Chapter 13

Toolbars, Status Bars, Progress Bars, and CoolbarsToolbarsEvery windows user knows about toolbars; they are those bars at the top of a windows that are fil led with buttons and sometimes other controls l ike combo boxes.

A toolbar contains buttons that correspond to items in appl ication’s menu, providing an easy interface for the user to reach frequently used funct ions and commands. In this way, toolbars can make l i fe a lot easier for the user. The user can also customize toolbars; double-c l icking a toolbar at runtime opens the customize toolbar dialog box, which al lows the user to hide, d isplay, or rearrange toolbar buttons.

You create a toolbar by adding a toolbar control to a form, and to do that, you select Project > Components menu item, then cl ick the Controls tab in the Component d ialog box, select the Microsoft Windows Common Controls i tem, and cl ick on OK to c lose the Components dialog box. This adds the Toolbar Control to the toolbox.

To add buttons to a toolbar, you add button objects to i ts Buttons col lect ion, usual ly by working with the toolbar’s property pages. Each button can have text and or an image. Set text with the Caption property and image with the Image property for each button object. At run t ime, you can add or remove buttons from the Buttons col lection using Add and Remove methods.

Adding a Toolbar to a Form Select the Project > Components > Controls tab Select Microsoft Windows Common Controls i tem, and cl ick OK.

This adds the toolbar control to the Visual Basic Toolbox. To place a toolbar in your form, just double cl ick the Toolbar Control tool .

Aligning Toolbars in a FormBy default toolbar al igns itself with the top of the cl ient area of the form. You can set the al ignment of the toolbar with the Al ign property, which can take these values

vbAl ignNone-0 vbAl ignTop-1(default) vbAl ignBottom-2 vbAl ignLeft-3 vbAl ignRight-4

Adding Buttons to a ToolbarYou add buttons to a toolbar control at design t ime by r ight-c l icking the control and cl icking the Properties i tem in the menu that appears. When the toolbar’s property pages open, cl ick the Buttons tab. Insert new buttons by c l icking the Insert Button button and remove a button with Remove Button button. When you add a new button to a toolbar, you can associate a picture or caption with it . For example, to give a button a caption, just fil l in the Caption box.

Each button gets a new Index value, which wi l l be passed to the cl ick event handler. You can also give each button a Key value, which is a str ing that you can use to ident i fy the button.

When you’re done, c l ick OK button to close the toolbar’s property pages. Now that you’ve instal led buttons in your toolbar, how do you handle button c l icks?

Handling toolbar buttons ClicksTo make buttons active use toolbar control ’s ButtonCl ick event.

Private Sub Toolbar1_ButtonCl ick( ByVal Button As ComctlL ib.Button)

End Sub

The button the user c l icked is passed to us in this event handler procedure, and we can determine which button was cl icked by checking either the buttons Index or Key properties. For example, we can indicate to users which button they cl icked with a message box and the Index property this way:

Al l buttons in a toolbar have an Index value by default, so this code is ready to go. When the user cl icks a button, we report which button the user cl icked.

Page 72: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 72

Besides using Index property, you can also give each buttons Key property text str ing. Then you use a Select Case statement to determine which button was cl icked, l ike this:

Pr ivate Sub Toolbar1_ButtonCl ick( ByVal Button As ComctlL ib.Button )

Select Case Button.KeyCase “OpenFi le”

FrmOpenFi le.ShowCase “SaveFi le”

FrmSavefile.ShowCase “CloseFi le”

FrmCloseFi le.ShowEnd Select

End Sub

Connecting Toolbar buttons to Menu ItemsYou can cal l the menu item’s Cl ick event handler when the button is cl icked.

Private Sub Toolbar1_ButtonCl ick( ByVal Button As ComctlL ib.Button )

Select Case Button.KeyCase “OpenFi le”

MnuFi leOpen_Cl ickCase “SaveFi le”

MnuFi leSave_Cl ickCase “CloseFi le”

MnuFi leClose_Cl ickEnd Select

End Sub

Adding Separators to a ToolbarYou can group the buttons in a Toolbar control using Separators. In menus, separators appear as sol id l ines, but in toolbars, separator just appear as blank spaces, sett ing groups of buttons apart.

For Example, Insert a new button to the Toolbar and set i ts style property to tbrSeparator. Now add other buttons and cl ick OK. You’l l see that the separator puts some distance between the buttons.

Adding Images to Toolbar ButtonsYou can give toolbar buttons an image i f you place those images into an image l ist control . Imagel ists are Windows common controls just as toolbars, so add an image l ist to your form. To place images do the fol lowing

Right_cl ick the image l ist tool Select the properties menu item Click the images tab in property pages Click insert picture button to insert the images you want, and cl ick OK

Now you need to associate the image control with toolbar, and you do that in the toolbar’s property pages

Right c l ick the toolbar and select properties to open property pages Click the buttons tab in the property pages Enter the index of the image in the image control want to connect to the

button Click OK to c lose

When you run the program, the images appear on toolbar.You can also connect an image control to a toolbar at run t ime, using toolbar’s ImageList property

Private Sub Command1_Cl ick( )Toolbar1.ImageList=ImageList1

End Sub

Adding Check (Toggle) Buttons to a ToolbarThe way toolbars handle check mark is, instead of displaying checkmarks to keep a button depressed once it ’s been pressed. In this way, you can show toggle states.

Let’s use an example.

To make a toolbar button a “check” button, you must set i ts Style property to tbrCheck, and you do that in toolbar’s property pages. Right-c l ick the toolbar and select properties to open property pages. Cl ick the buttons tab, select the button you want to work with,

Page 73: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 73

and set i ts style to tbrCheck. Now when the user c l icks the button, i t stays cl icked, unti l the user cl icks i t again.

Creating Button Groups in a ToolbarYou can setup groups of mutual ly exclusive buttons in toolbars, just as you can with groups of opt ion buttons

To create a button group, do the fol lowing

Open the toolbar’s property pages by r ight cl icking the toolbar and selecting the Properties i tem

Click the buttons tab Select the button in the button group, and set i ts style to tbrButtonGroup in style

box Repeat step 3 for other buttons in the button group Click Ok to c lose Property pages

When the user cl icks one to select i t , the others wi l l toggle off. Button groups can be very useful in a toolbar anyt ime opt ion buttons would come in handy in a toolbar, just use button group instead.

Adding Combo Boxes and Other Controls to a Toolbar

You can add combo boxes or other controls to a toolbar easi ly; just set aside space in the toolbar by sett ing a button’s Style property to the tbrPlaceholder. Just fol low the steps

Right-c l ick the toolbar Click the buttons tab in the property pages that open Insert a new button where you want the Combo box to go Set the new buttons style property to tbrPlaceHolder in the box labeled Style. This

means that button won’t appear-there’l l only be a b lank space, and we’l l place our combo box there.

Set the width of the space you want to leave for the combo box by entering a twip value in the box labeled Width:

Close the property pages by cl icking OK Click the Combo box control tool in the toolbox, and draw a new combo box in the

new space in the toolbar. Add the items you want in the combo box in the Properties window’s List property Connect the code you want to the combo box. For e.g. , Here we respond to combo

box cl icks and text entry by displaying a message box

Private Sub Combo1_Change( )

MsgBox “You Entered” & Combo1.Text

End Sub

Private Sub Combo1_Cl ick( )

MsgBox “You Selected” & Combo1.Text

End Sub

Setting ToolTips for Toolbar ButtonsGiving ToolTip for a button is an easy process. Al l you need to do to give a button a tool t ip is to set i ts ToolTipText property.

To set the ToolTipText property, r ight cl ick the toolbar, choose Properties to open Property pages, c l ick the buttons tab, select the button, place the ToolTip text in the ToolTipText box.

Letting the user customize the toolbarYou can let the user customize the toolbar. Just set the Al lowCustomize property to True. When the user double c l icks the toolbar, the Customize Toolbar dialog appears. Users can customize the toolbar as they l ike using that dialog box.

Adding Toolbar Buttons at RuntimeI t is possible to add buttons to a toolbar at runtime. To add a new button when the user cl icks a button, we start by declaring a new Button object. Next we add a new button to the toolbar’s buttons col lect ion, which is how it stores it buttons internal ly. Use the Buttons Col lect ion’s Add method. Now we’re free to set the button’s style. Here, we make it s standard button by sett ing the Style property to tbrDefault. We can also give the new button a caption, final ly give a ToolTip for the button.

Page 74: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 74

Private Sub Command1_Cl ick ()

Dim Button1 As ButtonSet Button1=Toolbar1.Buttons.Add( )Button1.Style=tbrDefaultButton1.Caption=”New Button”Button1.ToolTipText=”New Button”

End Sub

And that’s i t- the new button is act ive. I t has been added to the Buttons col lection of the toolbar control , which means it has its own Index value. Those Index values wi l l be passed to the ButtonCl ick handler, and we can make use of the index this way.

Private Sub ToolBar1_ButtonCl ick( ByVal Button As ComctlLib.Button)

MsgBox “You Cl icked button” & Button. Index

End Sub

Status BarsStatus bars appear at the bottom of windows and usual ly hold several panels in which you can display text. The status bar is there to give feedback to the user on program operation, as wel l as other i tems l ike t ime, day or key states such as Caps Lock or Ins key. Although status bars usual ly display text in panels, there is s imple status bar style that makes the status bar function as one long panel. Status bars are bui lt around the Panels col lect ion, which holds the panels in the status bar. Up to 16 panel objects can be contained in the col lection. each object can display an image and text. You can change the text, images, or widths of any panel object , using Text, Picture, and width propert ies. To add panel objects at design t ime, r ight-c l ick the status bar, and c l ick Properties to display the Property pages dialog box. You add the status bar control tool to the toolbox using Project> Components>Controls>Microsoft Windows Common Controls.

Adding a Status bar to the program

Select the Properties > Components Click Controls Tab Select Microsoft Windows Common Controls 6.0 and Cl ick OK

This adds the status bar control to toolbox. Cl ick and draw the status bar on your form

Aligning Status bars in a FormBy default status bar al ign itself with the bottom of the c l ient area of form. You can set the al ignment of the status bar with its Al ign property, which takes these values

vbAl ignNone-0 vbAl ignTop-1 (default) vbAl ignBotton-2 vbAl ignLeft-3 vbAl ignRight-4

Adding Panels to a Status BarA status bar control has Panels col lection, and you add the panels you want to that col lection. To do that at design t ime, fol low these steps

Right-Cl ick the status bar, and select the Properties i tem in the menu that opens

Click the Panels tab in the Property pages Click the Insert panel button as many t imes as you want panels in your

status bar Close the property pages by cl icking OK

It ’s also easy to add a new status bar panel at runtime- just use the Panels col lection’s Add method. Here’s an example to add panels to a status bar

Private Sub Command1_Cl ick( )

Dim panel5 As PanelSet panel5=StatusBar1.Panels.Add( )Panel5.Text=”Status: OK”

End Sub

Page 75: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 75

Displaying Text in PanelsThe text in a status bar is displayed in the status bar’s panels. Displaying text in a status bar’s panel is easy-just select the panel you want to work with as the index into the status bar’s Panels col lection, and use that panel’s text property. Here’s an example to display OK in panel

Private Sub Command1_Cl ick()StatusBar1.Panels(1).Text=”OK”

End Sub

Displaying Time, Dates and Key States in Status barTo display t ime, date or key states in your panel, just r ight c l ick the status bar, select the Properties i tem in the menu that appears, c l ick the Panels tab, select the panel you want to work with, and set the Style property in the box labeled Style to one of the fo l lowing:

sbrText-0 (default); text and/or a b itmap. Displays text in the Text property sbrCaps-1; Caps Lock Key. Displays the letters “CAPS” in bold when Caps

Lock is enabled, and dimmed when disabled. SbrNum-2; Num Lock Key. Displays the letters “NUM” in bold when the Num

Lock key is enabled, and dimmed when disabled SbrIns-3; Insert Key. Displays the letters “ INS” in bold when the Insert key is

enabled, and dimmed when disabled SbrScrl-4; Scrol l Lock Key. Displays the letters “SCRL” in bold when Scrol l

Lock is enabled, and dimmed when disabled. SbrTime-5; t ime. Displays the current t ime in the System format. SbrDate-6; date. Displays the current date in the system format. SbrKana-7; Kana Lock. Displays the letters “KANA” in bold when kana lock is

enabled, and dimmed when disabled. This feature is enabled on Japanese Operat ing Systems only

Customizing a Status Bar panel’s AppearanceYou can customize the appearance of the panels in a status bar with the Bevel, AutoSize, and Al ignment properties. The Bevel property specifies whether the panel wi l l have an inset bevel, raised, or none at al l . Here’s how you can set the Bevel property:

sbrNoBevel-0; the Panel displays no bevel, and text looks l ike it is displayed r ight on the status bar.

sbrInset-1; the Panel appears to be sunk into the Status bar sbrRaised-2; the Panel appears to be raised above the status bar

The AutoSize property determines how a panel wi l l resize itself when the user resizes its container. Here are the sett ings for the AutoSize property:

sbrNoAutoSize-0; None. No autosizing occurs. The width of the panel is always and exactly that specified by the Width property

sbrSpring-1; Spring. When the parent form resizes and there is extra space avai lable, al l panels with this sett ing divide the space and grow accordingly. The panel’s width never fal ls below that specified by MinWidth property.

sbrContents-2; Content. The panel is resized to fit i ts contents

the Al ignment property indicates how the text or image in a panel wi l l al ign in the panel. The sett ings for the Al ignment property are as fo l lows:

sbrLeft-0; text appears left- justified and to the r ight of any bitmap sbrCenter-1; text appears centered and to the r ight of any bitmap sbrRight-2; text appears r ight- just ified but to the left of any bitmap

Displaying Images in Status barStatus bar panels have Picture property to place images on it .

Right c l ick the status bar, and select Propert ies Click the panels tab in the Property pages. Select the panel you want to work with Set the panel’s Picture property by cl icking the Browse button in the box labeled

Picture. Select the picture to d isplay Close the property pages by cl icking OK

To set a status bar panel’s image at run t ime, Here’s an example

Private Sub Command1_Cl ick( )

StatusBar1.Panels(1).Picture=Picture1.Picture

End Sub

Page 76: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 76

Handling Panel ClicksStatus bars certainly can handle events, and the most common are PanelCl ick and PanelDblCl ick. The event handler procedures for those events are passed the panel that was c l icked, as in this example. You can tel l which panel was c l icked by checking the Panel argument’s Index or Key propert ies.

Private Sub StatusBar1_PanelCl ick( ByVal Panel As ComctlL ib.Panel)

MsgBox “ You Cl icked panel” & panel. IndexEnd Sub

If you’ve set the Key properties of the panels in your status bar, you can set up a Select Case statement to see which panel is cl icked.

Private Sub StatusBar1_PanelCl ick(ByVal Panel As ConctlLib.Panel)

Select Case Panel.KeyCase “Date”

Panel.Text=Date$Case “Time”

Panel.Text=Time$End Select

End SubAdding New Panels to a Status bar at runtimeI t ’s easy to add a new status bar panel at runt ime-just use the Panels col lection’s Add method. Here’s an example where we add a panel to a status bar.

Private Sub Command1_Cl ick( )

Dim panel5 As PanelSet panel5=StatusBar1.Panels.Add()Panel5.Text=”Status:OK”

End Sub

Creating Simple Status Bars

There’s a way of using status bars without panels: by making the status bar a s imple status bar. You set i ts Style property to sbrSimple. Simple status bars have only one panel, and you set the text in that panel with the SimpleText property.

Here’s an example

Private Sub Command1_Cl ick( )

StatusBar1.SimpleText=”Status OK”

End Sub

Progress BarsProgress bars give the user some visual feed back on what’s happening during a t ime consuming operat ion. They present the user with a color bar that grows in the control to show how the operation is proceeding, usual ly from 0 to 100 percent. You can use a Progress bar when an operation wi l l take some time to finish. The progress bar’s Value property, which is not avai lable at design t ime determines how much of the control has been fil led. The Min and Max properties set the l imits of the control . You add the Progress Bar control tool to the toolbox by fol lowing the same steps to add the toolbar tool , because the Progress bar control is also part of the Microsoft Windows Common Controls.

Adding a Progress Bar to a FormYou can use progress bar controls to show the progress of a t ime-consuming operation. These controls d isplay a colored band that can grow or shrink as t imes goes on. To add a progress bar to a form, fol low these steps:

Select Project > Components Click the Controls tab Select the Microsoft Windows Common Controls and cl ick OK. This adds the

Progress bar control to the toolbox To place a progress bar to your form, just add it as any other control Set the progress bar’s Min and Max propert ies as desired to match the range

of the operation you’re report ing on.

Page 77: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 77

Using a Progress BarYou use a progress bar’s Value property to specify how much of the progress bar is

vis ible. as you might expect, sett ing Value to Min means none of the progress bar is vis ible, and sett ing it to Max means al l of i t is .

Let ’s see an example, in this case, we’ l l let the user c l ick a button to display a progress bar whose bar lengthens from Min to Max in 10 seconds. Add a progress bar, command button, and a t imer control to a form now. Set the t imer’s Interval property to 1000. We’ l l leave the progress bar’s Min property at 0 and its Max property at 100, the defaults.

When the form loads, we disable the t imer and set the progress bar’s Value to 0;

Private Sub Form_Load( )

Timer1.Enabled=FalseProgressBar1.Value=0

End Sub

When the user cl icks the command button, we want to start the progress bar, so we enable the t imer. We also set the progress bar back to 0

Private Sub Command1_Cl ick( )

ProgressBar1.ValueTimer1.Enabled=True

End Sub

Final ly, the Timer event handler, Timer1_Timer, we add a value of 10 to the progress bar’s Value property every second. We also check i f we’ve fil led the progress bar, and i f so, disable the t imer.

Private Sub Timer1_Timer( )

ProgressBar1.Value=ProgressBar1.Value+10If ProgressBar1.Value>=100 Then Timer1.Enabled=False

End Sub

CoolbarsCoolbars were first introduced in Microsoft Internet Explorer, and they are toolbars that present controls in bands. Users can adjust these bands by dragging a gripper, which appears at left in a band. In this way, users can configure the coolbar by sl iding the bands around as they want. One popular use of coolbar is to display toolbars in the bands of that coolbar, al lowing users to move those toolbars around as they want.

Page 78: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 78

Chapter 14

CommonDialog ControlThe CommonDialog control exposes the dialogs bui lt into windows. Microsoft has created standard dia logs for many of the common tasks user face, such as choosing printer sett ings, opening and saving files, changing fonts, and selecting and defining colors. Many commercial appl ications use these common dialog boxes. Using common dialog boxes saves you a substant ial amount of work and lends your programs professional appearance, giving them a consistency that users have grown to expect.

Common DialogThis control provides an easy way to produce standard dialog boxes such as Fi le Open, Fi le Save, Pr int, Select Font, and Choose Color. This saves you from having to re-create standard dia log boxes for every appl ication. The action property determines which kind of dialog box to display and immediately displays it . You can also use the Show methods to provide a better way of using CommonDialog control . To add a CommonDialog control Choose Project > Components > Microsoft CommonDialog Control .

Common Dialogs

Dialog Purpose

Color Let the user choose a colorFont Let the user choose a fontHelp Show the user helpOpen Let the user open a filePrinter Let the user change the printer sett ingsSave Let the user save a file

Properties of Common Dialog Control

Property To Do this…

Action Specify the dialog to displayCancelError Determine whether an error is generated upon CancelColor Read or set the selected colorCopies Read or set the no. of copies to be printedDefaultExt Set the default extension for the dialog boxDialogTit le Set the caption of d ialog box t it le barFi leName Read or set the path and name of the file to open or saveFi leTit le Read the name of file to open or saveFi lter Read or set the Fi l ter for the kinds of files the file l ist displaysFi l terIndex Read or set the index no. of the filter for the default patternFlags Set various opt ions for each dialog box

FontBold, FontItal icFontStr ikethru, FontUnderLine Read or ser special effects for this objects fontFontName Read or set the name of the font for the objectFontSize Read or set the size of font for the objectFromPage, ToPage Read or set the values of page rangehDC Read the windows device handle for this objectHelpCommand Set the kind of help requestHelpfile set the name of help file to displayHelpKey set the keyword for the help file to search forInitDir Read or set Init ial diary to open fileMax, Min Set the smallest and largest font displayedMax, Min Set the smallest and largest page numbers to printMaxFi leSize Set the maximum length of filename used in Fi lename propertyPrinterDefault Determine whether changes in Print Dia log affect default sett ings

Methods of CommonDialog Control

Method To Do this

ShowColor Display the Color DialogShowFont Display the Font Dia logShowHelp Invoke Winhelp.EXEShowOpen Display Fi le Open DialogShowPrinter Display Printer DialogShowSave Display Save As Dialog

You can also use the different Action property value to show different Dia log boxes

Page 79: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 79

Action To Do this..

1 Displays Open Dialog2 Displays Save Dialog3 Displays Color Dialog4 Displays Font Dialog5 Displays Printer Dialog6 Displays Help Dialog

Open & Save As :These dia log boxes let the user to open or save a file. They have areas for choosing drives, directories, filenames, a l ist of avai lable filenames, a l ist of patterns, the option to open file readonly, and advanced opt ions for opening files on a network.

E.g. :

Pr ivate Sub CmdOpen_Cl ick( )CMDialog1.DefaultExt=”*.BMP”CMDialog1.DialogTit le=”Place Graphic Fi le”CMDialog1.Fi l ter=”Icons|*. ICO|Bitmaps|*.BMP|Metafiles|*.WMF”CMDialog1.Fi l terIndex=2CMDialog1.Flags=cdlOFNHelpButtonCMDialog1.ShowOpenPicture1.Picture=LoadPicture(CMDialog1.Fi lename)

End Sub

Color : - The Color common dia log box lets the user choose a color from a palette or create new colors. I t shows the actual palette colors, and when expanded to enable the creation of new colors, shows the whole color gamut and has input boxes for both HSV (Hue, Saturation, Value) and RGB ( Red, Green, Blue) values.

E.g. :Pr ivate Sub CmdColor_Cl ick( )

CMDialog1.Color=QBColor(1)CMDialog1.Flags=cdlCCRGBInit or cdlCCFul lOpenCMDialog1.ShowColorText1.BackColor= CMDialog1.Color

End Sub

Fonts : - The Font Common dialog box lets the user choose a font. I t has combo boxes l ist ing the names of al l the avai lable fonts, colors, s izes, and styles particular to the system the program is running on. I t shows the selected font and attr ibutes in a sample window. Some properties of font dialog need to have flags set before you can use them. Color, FontBold, FontItal ic , FontStr ikethru and FontUnderLine al l need the Effects flag set. Min and Max need LimitSize set before they can take effect. WYSYWIG needs to have both ScreenFonts and PrinterFonts set too. Make sure you set atleast one of ScreenFonts, Pr interFonts, or Both before cal l ing the Dialog box, other wise the “No Fonts Exist” error occurs.

E.g. :Pr ivate Sub CmdFont_Cl ick ( )

CMDialog1.Flags=cdlCFBoth or cdlCFHelpButton or cdlCFEffects or CdlCFTTonly

CMDialog1.FontBold=Text1.FontBoldCMDialog1.FontItal ic=Text1.FontIta l icCMDialog1.FontUnderLine=Text1.FontUnderLineCMDialog1.FontStr ikethru=Text1.FontStr ikethruCMDialog1.Color=Text1.ForeColorCMDialog1.FontName=Text1.FontNameCMDialog1.FontSize=Text1.FontSizeCMDialog1.ShowFont

Text1.FontBold= CMDialog1.FontBoldText1.FontIta l ic= CMDialog1.FontItal icText1.FontStr ikethru= CMDialog1.FontStr ikethruText1.FontUnderLine= CMDialog1.FontUnderLineText1.ForeColor= CMDialog1.ColorText1.FontName= CMDialog1.FontNameText1.FontSize=CMDialog1.FontSize

End Sub

Print : - The Print Common dialog box lets the user specify how material is to be printed. It has areas that enable input of page ranges, number of copies, pr int qual ity, col lat ion, and print to file. It also has command buttons that al low for sett ing up the current printer or specifying a different printer. Note that the dialog box does not do any actual print ing; your code st i l l has to do that.

Page 80: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 80

E.g.:Pr ivate Sub CmdPrint_Cl ick( )

CMDialog1.Copies=3CMDialog1.Flags=cdlPDAllPages or cdlPDCol lateCMDialog1.ShowPrinter

End Sub

Help : - The Help Common dialog box action doesn’t real ly bring up a dia log box. Instead, i t cal ls WINHELP.EXE and passes it the proper parameters for context-sensit ive help, keyword searches, or even help on Help.

E.g. :Pr ivate Sub CmdHelp_Cl ick ( )

CMDialog1.HelpFi le=”MyApp.HLP”CMDialog1.HelpCommand=vbHelpKeyCMDialog1.HelpKey=”Graphing”CMDialog1.ShowHelp

End Sub

Page 81: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 81

Chapter 15

Flex Grid ControlFlexgrid control:-An MS flex grid control in VISUAL BASIC is used to create appl ications that present informations in rows and columns. It displays informations in cel ls. The intersection of a row and column is cal led a cel l . The user can select a cel l at run t ime using mouse or arrow keys, but cannot edit or alter the cel l contents. We can place text or a picture in MS flex grid.

The row and column property specifies the current cel l . Text property refers the contents of current cel l . The column width property is used to change at the width of column, row height to change the height of row. The rows and columns properties are used to determine the no.of rows and columns in MS flex grid. Two kinds of rows and columns are created in flex grid control . They are fixed and non-fixed.

Basic methods , Events, and Properties dealing with Flex Grid Control

AddItem:- The AddItem method adds an item to the l ist of a grid. When AddItem method executes, the value of the str ing expression specified is added to the grid. You can specify the exact p lacement of the new item in the grid by provid ing the Index argument. The index number must be not less than 0 and not greater than the value of Rows property. You can add data to more than one column within the same row by using the tab character Chr (9) to del imit each columns data.

SyntaxObject.AddItem Item [, index]

E.g. :Pr ivate Sub Form_Load ()

Flex. AddItem "ICES", 1Flex. AddItem "I", 2Flex. AddItem "C", 3Flex. AddItem "IC" & Chr (9) & "ES", 4Flex. AddItem "yas", 6

End Sub

Al lowBigSelect ion:- This property reads or sets whether an ent ire row or column can be selected by c l icking on its header. By default this property is True. I f there is no fixed rows or columns, then this property has no effect.

SyntaxObject.Al lowBigSelection=Boolean

E.g.:Flex.Al lowBigSelection=True

Al lowUserResizing:- This property reads or sets whether the user can resize the rows and columns. This property has the values flexresizenone, flexresizecolumns, flexresizerows and flexresizeboth. I f this property is set user can resize the columns and rows by moving the mouse pointer to the header area and dragging the gridl ine which needs to be moved.

SyntaxObject.Al lowUserResizing=resizing

E.g.:Flex.Al lowUserResizing=flexResizeBoth

BackColor, BackColorBkg, BackColorFixed, BackColorSel, Cel lBackColor:- Used to read or set the background color of grid elements. Except Cel lBakColor property al l other properties specified above can be set at design t ime. The BackColor property sets the background color of the main nonfixed grid cel ls. The BackColorSel property sets the background color of the selection. The BackColorBkg property sets the background color of the area behind the grid, which may only, v isib le when you scrol l al l the way to the r ight or to the bottom. The BackColorFixed property sets the background color of the fixed rows and columns of the grid. Cel lBackColor property changes the background color of the current cel l , which is indicated by the current sett ing of row and column value.

SyntaxObject.BackColor=colorObject.BackColorBkg=colorObject.BackColorFixed=colorObject.BackColorSel=colorObject.Cel lBackColor=color

Page 82: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 82

The different Color arguments are vbBlack, vbBlue, vbCyan, vbGreen, vbMagenta, vbRed, vbWhite, vbYel low, &HBBGGRR or RGB(r,g,b)

E.g. :Pr ivate Sub Form_Load( )

Flex.BackColor=vbRedFlex.BackColorBkg=vbBlueFlex.BackColorFixed=vbCyanFlex.BackColorSel=&HC0C0C0Flex.Cel lBackColor=RGB(0,100,124)

End Sub

Cel lAl ignment:- Use the Grid’s Cel lAl ignment property to read or set the al ignment of the act ive cel l ’s data. This property is not avai lable at design t ime; read and write at runtime.

SyntaxObject.Cel lAl ignment=al ignment

This property lets you read or set the al ignment of individual cel ls. This property only affects the act ivecel l designated by the Row and Col properties.

The different a l ignment propert ies are flexAl ignLeftTop, flexLeftAl ignLeftCenter, flexAl ignLeftBottom, flexAl ignCenterTop, flexAl ignCenterCenter, flexAl ignCenterBottom, flexAl ignRightTop, flexAl ignRightCenter, flexAl ignRightBottom, and flexAl ignGeneral

E.g. :Flex.Cel lAl ignment=flexAl ignLeftBottom

CellHeight, Cel lLeft, Cel lTop, Cel lWidth :- Use these propert ies read the size or posit ion of the current cel l . This property is not avai lable at design t ime and is read-only at runtime.

Syntax

Object.Cel lHeight [as integer]Object.Cel lLeft [as integer]Object.Cel lTop [as integer]Object.Cel lWidth [as integer]

E.g. :Text1.Height=Flex.Cel lHeightText1.Left=Flex.Cel lLeftText1.Top=Flex.Cel lTopText1.Width=Flex.Cel lWidth

Clear:- This method clears al l text, graphics etc within a grid. This method does not reset any foreground or background properties of the grid and only affects the data within the cel ls.

SyntaxObject.Celar

E.g. :Pr ivate Sub CmdClear_Cl ick()

Flex.Clear

End Sub

Col, Row, ColSel, RowSel :- Use the Col, Row, RowSel, ColSel propert ies to determine or set the active cel l and range of selected cel ls in a grid. Once an active cel l is set , you can use other properties on that cel l , such as Text. This property is not avai lable at design t ime and is readable and writable at runtime.

SyntaxObject.Col=ColnumberObject.Row=RownumberObject.ColSel=ColnumberObject.RowSel= Rownumber

E.g. :Flex.Row=1Flex.Col=1Flex.ColSel=Flex.Cols-1Flex.RowSel=Flex.Rows-1

ColAl ignment:- Use this property of a grid to read or set the al ignment of a column’s data. This property is only avai lable at run t ime. i t is only avai lable for nonfixed columns.

SyntaxObject.ColAl ignment(columnnumber)=al ignment

Page 83: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 83

The al ignment argument has the value flexAl ignLeftTop (Default) , flexAl ignLeftCenter, flexAl ignLeftBottom, flexAl ignCenterTop, flexAl ignCenterCenter, flexAl ignCenterBottom, flexAl ignRightTop, flexAl ignRightCenter, flexAl ignRightBottom and flexAl ignGeneral .

E.g. :F lex.ColAl ignment(5)=flexAl ignRightTop

Cols, Rows:- Use these properties to read or set the total number of columns or rows in a grid. This property is not avai lable at design t ime and is readable and writable at runtime. Using this property you can find the index of Last Column or Row as Cols-1 or Rows-1 because index starts at 0.

SyntaxOblect.Cols=columnsObject.Rows=Rows

E.g.:Pr ivate Sub CmdAddClick()

Flex.Cols=Flex.Cols+1Flex.Rows=Flex.Rows-1

End Sub

ColWidth, RowHeight:- The ColWidth property reads or sets the width of a column in a grid; the RowHeight property reads or sets the height of a row in a grid. These properties are only avai lable at runtime. The sizes are always expressed in the unit Twips, with 1440 twips per inch.

SyntaxObject.Colwidth(columnnumber)=widthObject.RowHeight(Rownumber)=Height

E.g. :Pr ivate Sub Form_Load()

Flex.ColWidth(0)=400Flex.RowHeight(1)=1000

End Sub

FixedAl ignment: - Use this property to read or set the al ignment of data in the fixed cel ls of a grid’s column. This property is read and write only at runt ime.

SyntaxObject.FixedAl ignment(columnnumber)=al ignment

The al ignment argument has the value flexAl ignLeftTop (Default) , flexAl ignLeftCenter, flexAl ignLeftBottom, flexAl ignCenterTop, flexAl ignCenterCenter, flexAl ignCenterBottom, flexAl ignRightTop, flexAl ignRightCenter, flexAl ignRightBottom and flexAl ignGeneral .

E.g. :F lex.FixedAl ignment(1)=flexALignRightTop

FixedCols, F ixedRows:- Use these properties to read or set the number of fixed rows or columns on the left and top of a grid. F ixed Rows and Columns are typical ly used for headings.

SyntaxObject.FixedCols=columnsObject.FixedRows=Rows

E.g.:Flex.FixedCols=1Flex.FixedRows=1

ForeColor, ForeColorFixed, ForeColorSel, Cel lForeColor:- Use these propert ies to set the text or foreground color of grid elements. Al l the propert ies except Cel lForecolor are avai lable at design t ime; Cel lForeColor is only avai lable at run t ime. The ForeColor property sets the text color of nonfixed cel ls. The ForeColorSel property sets the text color of the selection. The ForeColorFixed sets the foreground color of fixed rows and columns of the grid. The Cel lForeColor property can be used to change the text color of the current cel l , which is indicated by Row and Col properties.

SyntaxObject.ForeColor=colorObject.ForeColorFixed=colorObject.ForeColorSel=colorObject.Cel lForeColor=color

The different Color arguments are vbBlack, vbBlue, vbCyan, vbGreen, vbMagenta, vbRed, vbWhite, vbYel low, &HBBGGRR or RGB(r,g,b)

Page 84: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 84

E.g.:Pr ivate Sub Form_Load( )

Flex.ForeColor = vbRed F lex.ForeColorFixed = vbCyan F lex.ForeColorSel = vbGreen F lex.Cel lForeColor = vbBlue

End Sub

GridLines, GridLinesFixed:- Use these propert ies to read or set the style of a grid’s gridl ines in the nonfixed and fixed cel ls. Grid l ines are the l ight gray l ines that visual ly separate individual cel ls.

SyntaxObject.GridLines=linestyleObject.GridLinesFixed=linestyle

Linestyle argument has the values flexGridNone, flexGridFlat (Default) , flexGridInset, and flexGridRaised.

E.g. :Pr ivate Sub Form_Load()

Flex.GridLines=flexGridNoneFlex.GridLinesFixed=flexGridRaised

End Sub

GridLineWidth:- Use this property to set the size of l ines between the grid cel ls in a grid. This property is avai lable at design t ime and is readable and writable at runt ime. The width is specified in pixels.

SyntaxObject.GridLineWidth=width

E.g.:Flex.GridLineWidth=7

MouseCol, MouseRow :- Use these propert ies to read the cel l the mouse pointer is currently over. These propert ies are only avai lable at run t ime.

SyntaxObject.MouseCol=columnObject.MouseRow=Row

E.g.:Pr ivate Sub Flex_Cl ick()

Text1.Text=”Row” & Flex.RowText2.Text=”Col” & Flex.Col

End Sub

RemoveItem:- The RemoveItem method deletes an item from the l ist in a grid. This method deletes the row indicated by index number argument from a grid. When an item is removed from the grid, the index number of the each entry in the l ist fol lowed the removed item is decremented. The rows property for the control is also decremented.

SyntaxObject.RemoveItem Index

E.g.:Pr ivate Sub CmdRemoveRow_Click()

Flex.RemoveItem Flex.Row

End Sub

SelectionMode:- This property reads or sets whether any cel l range can be selected; only rows can be selected, or only columns can be selected.

SyntaxObject.SelectionMode=mode

The Mode argument has the value flexSelect ionFree (Default) , flexSelect ionByRow, and flexSelect ionByColumn.

E.g. :Flex.SelectionMode=flexSelectionByRow

Text:- The Text property is used to read or set the text of the current cel l entry in a grid. The act ive cel l is set with the Row and Col propert ies.

SyntaxObject.Text=Textstr ing

Page 85: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 85

E.g.:Pr ivate Sub CmdAdd_Cl ick( )

Flex.Row=2Flex.Col=3Flex.Text=Text1.Text

End Sub

TextMatrix:- Returns or sets the text contents of an arbitrary cel l . This property a l lows you to set or retr ieve the contents of a cel l without changing the Row and Col propert ies.

SyntaxObject.TextMatrix(rowindex, col index) [=str ing]

Rowindex, Col index are Integer, that specifies which cel l to read or write.Str ing is a str ing expression containing the contents of an arbitrary cel l .

E.g. :F lex.TextMatrix(1,1)=234

TextStyle, TextStyleFixed, Cel lTextStyle: - Use these properties to read or set the style of the text within a grid’s cel ls. The TextStyle affects the appearance of the text within the nonfixed Rows. The TextStyleFixed property reads or sets the style of a l l fixed Rows. The Cel lTextStyle property reads or sets the sty le of the active cel l designated by the Col and Row propert ies.

SyntaxObject.TextStyle=TextstyleObject.TextStyleFixed=TextstyleObject.Cel lTextStyle=Textstyle

The Textstyle argument has the values flexTextFlat, flexTextRaised, flexTextInset, flexTextRaisedLight, and flexTextInsetLight.

E.g. :Pr ivate Sub CmdStyle_Cl ick()

Flex.TextStyle=flexTextRaisedFlex.TextStyleFixed=flexTextInsetFlex.Row=2Flex.Col=2Flex.Cel lTextStyle=flexTextRaisedLight

End Sub

WordWrap:- The WordWrap property reads or sets whether the text within the active cel l should wrap within the cel l i f i t ’s longer than the cel l is wide.

SyntaxObject.WordWrap=Boolean

E.g.:Pr ivate Sub Command1_Cl ick()

Flex.Col=2Flex.Row=2Flex.Text=”Indian Computer Education”Flex.WordWrap=True

End Sub

Page 86: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 86

Chapter 16

Building Classes and CollectionsObject Oriented programming (OOP) is nothing new, only now are the mainstream tools such as VISUAL BASIC real ly integrating its concepts. OOP is real ly nothing more than translat ing real-world business concepts into logical entit ies the computer can understand.

In VISUAL BASIC, objects have three major components

Properties Properties are l ike the fields of a user-defined type. They contain data about the object . Property procedures provide control led access to data stored within an object.

Methods These are actions that are associated with the object. You may have a Print or Save method, for instance. Methods operate on the data in an object.

Events You can define and tr igger events on objects, in much the same way controls and forms receive events as the user does various operations.

These major components can also be further subdivided into two groups.

Public The entire appl icat ion can access the property, method, or event.

Private Only the object i tself can access the property, method or event.

Besides having single object, you can also create froups of objects. These groups are cal led Col lections. A number of col lections are bui lt into the VISUAL BASIC language and object model, such as the Controls and Forms col lections. Col lection names are usual ly the same as their component object’s name made into a plural .

Object Oriented Programming also provides a number of advantages over regular programming. The first is that business logic can be encapsulated within an object . For instance, i f you decide that a variety of val idat ions need to be done on data, you can put that val idat ion code within the object. The object can cause an error to occur i f the data is inval id.

Encapsulation is also sometimes cal led data hiding. Because objects control access to the data within themselves, the data in each object is essent ial ly hidden from other code. Normally, each c lass has a series of property procedures, which are pieces of code used to retr ieve and modify the hidden values in an object, accordingly. I f a value in an object is not meant to be modified, i t is defined as private and not modifier is provided. Accessors can be designed to return different types of data. For instance, a value stored as a date variable could be returned as a formatted text str ing or even in another unit, such as days or hours.

Another feature of OOP is Polymorphism. It is a fancy word for real ly s imple concept. Both a car and a truck can be driven, parked, and repaired. As a programmer, you don’t have to worry about whether the object is a car or a truck- you just have to know it is a vehic le that supports the drive, park, and repair methods.

One common feature not supported in VISUAL BASIC is inheritance. Inheritance al lows you to set up parent-chi ld relationships between classes. A chi ld class contains al l the same properties, methods and events of i ts parent. I t can add or modify those class members as i t sees fit.

Building a Simple Class

Lets explain the Class using the fol lowing Customer ClassThis c lass has the properties shown below

Property Data Type Description

Custname String Customer NameCompany String Company NameAddress Str ing Address of CustomerPhone String Phone Number

To start bui lding your class, fol low these steps:

In a Standard Exe Project, add a New Class Module. Set the name of c lass to Ccustomer. Class names are normally prefixed with a C to

help dist inguish them from other data types. The first i tem to add to the Class module are the variables that represent each of

the properties of the c lass. These are private variables that are hidden from view by the class. Add the code from the fol lowing in Declarat ion section of your c lass module.

Option Expl icit

Page 87: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 87

Private mvarCustname As Str ingPrivate mvarCompany As Str ingPrivate mvarAddress As Str ingPrivate mvarPhone As Str ing

Each member variable is designed to be retr ieved and modified using Property procedures. You can bui ld property procedures corresponding to each variable using an Accessor and Modifier. The Property Get and Property Let subroutines are special ly bui lt for handl ing property access and modification. The fol lowing l ist creates accessor and modifier for each variable in Ccustomer Class.

Publ ic Property Let Custname ( ByVal s Input As Str ing )mvarCustname=sInput

End Property

Publ ic Property Get Custname ( )Company=mvarCustname

End Property

Publ ic Property Let Company ( ByVal s Input As Str ing )mvarCompany=sInput

End Property

Publ ic Property Get Company ( )Company=mvarCompany

End Property

Publ ic Property Let Address ( ByVal s Input As Str ing )mvarAddress=sInput

End Property

Publ ic Property Get Address ( )Address=mvarAddress

End Property

Publ ic Property Let Phone ( ByVal s Input As Str ing )mvarPhone=sInput

End Property

Publ ic Property Get Phone ( )Phone=mvarPhone

End Property

Now that you have a way to modify the object ’s data, you can add addit ional methods to provide more services. These methods are essentia l ly identical to Property procedures. The fo l lowing method returns True i f al l the required values have been set.

Publ ic Function IsVal id( ) As BooleanDim bval id As Boolean

bval id=Truebval id=bval id and mvarCustname <> “”bval id=bval id and mvarAddress <> “”bval id=bval id and mvarCompany <> “”IsVal id=bval id

End Function

Typical ly, Property procedures are only used for accessing and modifying member variables. In addit ion, Property procedures cannot accept addit ional arguments.

For instance, Property Let procedures are designed to be cal led as fol lows

Customer.Custname=”ICES”

This code cal ls the Property Let Procedure cal led Custname. In this cal l , no logical place is avai lable for addit ional parameters. I f you need more parameters, you

have to use subroutines and functions; they can accept any number of parameters.

Using Classes in Code and Forms

The fol lowing project wi l l show you how to use your Customer object with a form designed to manipulate it . You’ l l use the object to do some from data val idation using the IsVal id( ) method you bui lt . This feature demonstrates encapsulation of business logic

Page 88: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 88

within the Customer object. Instead of putt ing the logic in the form, you let the object determine i f i ts data is val id. Create a form with fol lowing controls and properties

Page 89: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 89

Control Property value

Form Name frmEditCustomerBorderStyle 3-Fixed Dialog

TextBox Name txtCustNameTextBox Name txtAddressTextBox Name txtCompanyTextBox Name txtPhoneCommand Button Name cmdOK

Caption OKCommand Button Name cmdCancel

Caption CancelCancel True

Now you have to bui ld both Add( ) and Edit ( ) method for this form. You’l l also need to declare an instance of CCustomer Class

Form Declarat ion Sect ion

Dim CurrentCustomer As CCustomer

Publ ic Function ADD ( ) As CCustomer

Set CurrentCustomer=New CCustomerMe.Show vbModalSet Add=CurrentCustomerUnload Me

End Function

Publ ic Function Edit( ObjCustomer As CCustomer)

Set CurrentCustomer= ObjCustomer

txtCustname.Text=CurrentCustomer.CustNametxtAddress.Text=CurrentCustomer.AddresstxtCompany.Text=CurrentCustomer.CompanytxtPhone.Text=CurrentCustomer.Phone

Me.Show vbModalUnload Me

End Function

This code wi l l either create a new object or load the data from an exist ing object into the fields on the form.

The next code you need to add takes care of updating each of the object’s properties as the user changes data on the form. Each textboxes change event also cal ls a new subroutine that checks to see i f data can be saved yet. The fol lowing l ists the code to add.

Private Sub CheckOKButton ( )CmdOK.Enabled=CurrentCustomer. IsVal id

End Sub

Private Sub txtCustname_change( )CurrentCustomer.Custname=txtCustname.TextCheckOKButton

End Sub

Private Sub txtCompany_change( )CurrentCustomer.Company=txtCompany.TextCheckOKButton

End Sub

Private Sub txtAddress_change( )CurrentCustomer.Address=txtAddress.TextCheckOKButton

End Sub

Private Sub txtPhone_change( )CurrentCustomer.Phone=txtPhone.TextCheckOKButton

End Sub

Page 90: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 90

The only other code required to make this form work is a subrout ine that cal ls either Add() or Edit() method of the form. This is , of course, just for test ing, but you need a way to try out your work. Add a new Form to your project by choosing Project > Add > Form. Add Two command buttons namely cmdADD and cmdEdit.Add the fol lowing code in the new form.

Option Expl icitDim ObjCustomer As Ccustomer

Private Sub cmdAdd_Cl ick( )Set ObjCustomer=frmEditCustomer.Add

End Sub

Private Sub cmdEdit_Cl ick( )FrmEditCustomer.Edit ObjCustomer

End Sub

Make the new form as your startup object from Project > Propert ies and run the Project.

Building Collections

As with most computer programs and databases, very few cases occur in which you’ l l be deal ing with a s ingle object or record. In most cases, you’l l need to work with a group of objects together as a unit . Although you could create an array of a particular class, arrays cannot have code associated with them. However, by bui lding a col lection class, you can combine your objects with associated code. For instance, you may have code to add a new object to the col lection or to retr ieve the number of objects currently being stored.

A col lect ion c lass is bui lt using a regular class module- no special col lection class exists. As you’ l l soon see, the col lect ion’s power is in i ts properties and methods. To demonstrate how col lections interact with c lasses, the fol lowing l ist shows the code for a new class named Ccontact, which contains address information about a part icular person

Option Expl icit

Pr ivate msCustName As Str ingPrivate msAddress As Str ingPrivate msCity As Str ingPrivate msState As Str ing

Publ ic Property Let CustName( ByVal vData As Str ing )msCustName=vData

End Property

Publ ic Property Get CustName( ) As Str ingCustName=msCustName

End Property

Publ ic Property Let Address( ByVal vData As Str ing )msAddress=vData

End Property

Publ ic Property Get Address( ) As Str ingAddress=msAddress

End Property

Publ ic Property Let City( ByVal vData As Str ing )msCity=vData

End Property

Publ ic Property Get City( ) As Str ingCity=msCity

End Property

Publ ic Property Let State( ByVal vData As Str ing )msState=vData

End Property

Publ ic Property Get State( ) As Str ingState=msState

End Property

Page 91: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 91

This is a fair ly s imple c lass with a few str ing properties and the associated accessors / modifiers to read and modify the data in the object. Although the code for this c lass can be bui lt with the Class Bui lder included with VISUAL BASIC.

Each col lect ion c lass need to support several standard properties and methods. These properties and methods are shown below

Name Type Description

Add Method Adds a new object to the col lectionCount Property Returns the number of objects in the col lectionItem Property Returns an object from the col lection, based on a number or a

key valueNewEnum Property Al lows code to i terate through a col lect ion using a For Each

statementRemove Method Removes a selected item from the col lection

Al l this code wi l l be automatical ly added and customized when you create a col lection class based on a simple class l ike Ccontact. Standard naming conventions suggest that col lection c lasses should be named with the plural of s imple class. For instance, the col lection c lass for Ccontact would be Ccontacts. The code the class bui lder bui lt for the Ccontacts col lect ion c lass is shown in fol lowing l ist

Option Expl icit

Pr ivate mCol as Col lection

Publ ic Function Add( State As Str ing, City As Str ing, Address As Str ing, Custname As

Str ing, Optional sKey As Str ing) As Ccontact

Dim ObjNewMember As CContactSet ObjNewMember=New CContact

ObjNewMember.State=StateObjNewMember.City=CityObjNewMember.Address=AddressObjNewMember.CustName=CustName

If Len(sKey) =0 ThenmCol.Add ObjNewMember

ElsemCol.Add ObjNewMember, sKey

End I f

End Function

Publ ic Property Get I tem( vntIndexKey As Variant) As CContactSet I tem=mCol(vnt IndexKey)

End Property

Publ ic Property Get Count( ) As LongCount=mCol.Count

End Property

Publ ic Sub Remove( vnt IndexKey As Variant)mCol.Remove vntIndexKey

End Sub

Publ ic Property Get NewEnum( ) As IUnknownSet NewEnum=mCol.[_NewEnum]

End Property

Private Sub Class_Init ial ize( )Set mCol=New Col lection

End Sub

Private Sub Class_Terminate( )Set mCol=Nothing

End Sub

A Col lection is responsible for informing the object how to load its data. It then simply adds the object to the col lection instead of actual ly fil l ing each object

i tself .

The Add( ) method is designed to accept al l the property values for a new CContact object. It creates a new CContact object by using the New keyword. Incidental ly,

using the New keyword causes the CContact’s Init ia l ize event to fire. Once the new object has been created, each of the properties is set .

Once the object has been created and fil led, i t is then added to the col lect ion. Objects added to a col lection can have a key value set for quick retr ieval. The

code provided only adds a key i f one was provided to the Add( ) method. As you’ l l see

Page 92: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 92

when you bui ld a col lect ion based on a database, the key value should a lways be added to enable quick retr ieval of the item from the col lection later. Keys cannot

be str ict ly numeric values, so i f you wish to use some unique ID as the basis for the key value, you’ l l need to add some text to i t as wel l . For instance, you can’t have

a key of 15, but you can have a key of Item 15. This is s imply a requirement of the col lection object.

Final ly, the new object is returned to the cal l ing code. This al lows the cal ler to use the object in whatever way is required. That’s real ly al l there is to the code. The rest of the code is s imply returning properties of the col lection or reimplementing methods of the col lection, such as the Remove( ) method. The only tr icky code is in the NewEnum property. This code should basical ly be left as is. This code al lows the For Each feature to work correct ly. As each object in the col lection is seen, For Each creates an enumerat ion code that the col lection can interpret. This code provides this funct ional ity for you.

Page 93: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 93

Chapter 17

Structured Query Language(SQL)SQL (structured Query Language)SQL is a programming language, which is evolved from an earl ier language cal led ‘sequel’ . Modern SQL has become a very powerful standard database programming language. MS Access uti l ises SQL for i ts standard programming language and it is used by VISUAL BASIC to manipulate and modify the database.

The differences between access SQL and most other implementat ions are very minor. Other databases using SQL are MSSQL Server , Oracle , Sybase.

Access comes with a complete set of SQL functional ity that includes a complete data definition language(DDL) , Data manipulation language(DML) . In VISUAL BASIC you can create and use SQL statements with in your program as wel l as use stored queries with in the database itself .

Different types of SQL:-

Queries fal l into two groups; they are DDL, DML. The DDL queries defines or alters the structure of the database, the DML queries act d irect ly upon the data contained in the database. In MS Access the DDL type of queries include Create, Alter, Drop.The DML queries include Select, Update, Insert and Delete.Queries can be further classified as join, union, parameter and other types depending on their structures and uses.

The basic structure of a SQL query has three parts:

1) Parameter declaration : - In the case of a parameter query, this part is used to supply the name and type the parameter.

2) Manipulative Statement : - The manipulat ive statement defines the act ion that the query is to perform upon the database.

3) Option Declaration : - With owner option, g ives the user owner permissions in a secure environment.

DDL Queries : - DDL queries are bui ld using a number of commands that can create, change or remove structure elements from the database. The fo l lowing l ists the commands of DDL query.

1) Alter table: - Used to alter(change) the structure of an exist ing table.

2) Create table: - Used to create tables in an exist ing database.

3) Create index:- To create indexes for exist ing tables.

4) Drop table:- To remove a table from the database.

5) Drop index:- To remove an index of an exist ing table. DDL queries not return any records and therefore are used only with the execute method of a database or query Def object.

Create queries :-

E.g.:- Create table stock(item text(25), qty number).

This query would create a table in the specified database with a name “stock” with one text fields, and one numeric field.

Create Index ab on stock (item)

Alter queries:-

To modify a column :

Alter table stock modify column item text(30).

To add a column :

Alter table stock add column itcode text(10)

Drop Queries:-

drop table stockdrop index ab on stock

Page 94: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 94

DML Queries:-DML queries provide the means to retr ieve the Recordsets to update data and add or delete records in a table. The fol lowing l ists the commands of DML queries.

Select : - Creates a recordset from one or more tables that satisfy specific cr iter ia.Insert : - Transfers a batch of data into the data tableUpdate : - Changes the data values of a part icular set of records.Delete : - Delete records from a table.

Select Queries : - It is the most used query type. Your appl ication would use the select query to create recordsets based on one or more tables that meet tables that meet a particular cr iter ia. Your appl ication can then manipulate these recordsets using the Data Access Objects propert ies and methods such as displaying, adding, edit ing, and deleting records as required.

Syntax:-SELECT [FIELD LIST] FROM [TABLE LIST] [WHERE (CONDITION)]GROUP BY [FIELD LIST] ORDER BY [FIELD LIST]

Where Clause:- The Where clause is used to specify the cr iter ia for select ing the records to be included in the result ing recordset. I f no where clause is used, then al l the records in the table(s) wi l l be returned. The cr iter ia requirements in the where clause are very flexible. You can use upto 40 expressions l inked by logical operators in your where clause. When using str ings as cr iter ia, you must wrap them in single or double quotes as in the examples. Dates require that you wrap them in the “#” character.

Use the fol lowing operators with where clause

Like Used for pattern matching E.g. :- 1) Select * From Stock Where I tem Like ’T*’ wi l l return any item with first

character ‘T’

2) Select * From Stock Where I tem Like ‘*V’ wi l l return any item with last character ‘V’

3) Select * From Stock Where Qty Like 87## wi l l return any qty between 8700 and 8799

4) Select * From Stock Where I tem Like ‘T??’ wi l l return any item with start ing character ‘T’ and

maximum three characters.

5) Select * From Stock Where Name Like “SM[EIY]TH” wi l l match SMETH, SMETH, SMYTH

6) Select * From ABC Where Item Like “DR[!U]G”wil l match al l combinat ions except DRUG

Equal to (=) :- Use this operator for Exact match

E.g.: Select * From Stock Where Qty= 10 wil l match al l records having qty 10

Not Equal to (<>, !=) :- Use this operator to match al l except given expression

E.g.: Select * From Stock Where Qty <> 10 wil l match al l records having qty not equal to 10

Greater than (>):- Use this operator to match al l records greater than given expression

E.g.: Select * From Stock Where Qty>10 wil l match al l records having qty greater than 10

Greater than or Equal to (>=):-Use this operator to match al l records greater than or equal to given expression

E.g.: Select * From Stock Where Qty >=10 wil l match al l records having qty greater than or equal to 10

Less Than (<):-Use this operator to match al l records Less than given expression

E.g.: Select * From Stock Where Qty<10 wil l match al l records having qty Less than 10

Less than or equal to(<=):- Use this operator to match al l records Less than or equal to given expression

E.g.: Select * From Stock Where Qty<=10 wil l match al l records having qty Less than or equal to 10

Between:- Use this operator to match numbers between two values (both included).

E.g. : Select * From Stock Where Qty between 10 and 20wil l match al l records having qty any number between 10 and 20

Page 95: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 95

IN:- Matches a Str ing within the Given List

E.g. : Select * From Stock Where Item IN(‘TV’, ‘VCR’, ‘VCP’) Wil l match items ‘TV’, ‘VCR’ and ‘VCP’

NOT:- use Not operator with Like, Between and IN to inverse the logical expression

E.g.: Select * From Stock Where Item Not Like ‘T*’Select * From Stock Where Item Not IN(‘TV’, ‘VCR’, ‘VCP’)Select * From Stock Where Item Not BETWEEN 10 and 20

E.g. 1) select * from stock2) select item,qty from stock3) select item,qty from stock where item=’tv’4) select item,qty from stock order by item

Delete Query : - used to delete records from a tableSyntax:- DELETE [FIELD LIST] FROM [TABLE LIST] [WHERE (CONDITION)]

E.g. :- Delete * from table1 where item=’tv’

Update Queries : - In may circumstances you wi l l want to do a batch update of new values for specified fields. To do this you can use update query. I t also supports a where clause to specify any condit ions.

Syntax:- UPDATE TABLENAME SET <FIELD NAME>=VALUE WHERE <CONDITION>

E.g.:- 1) Update stock set item=’tv’2) Update stock set qty=1003) Update stock set amount=qty*price4) Update employee set basic=basic+basic*10/100 where desig=”clerk”5) Update stock set qty=100,price=100, where item=”tv”

Insert into queries:- The insert into query is used to append new records to the end of an exist ing table or query and is also known as append query.

Syntax:- INSERT INTO <TABLE NAME>(field1,field2,field3…) values (value1,value2,value3…)

E.g.:- 1) INSERT INTO STOCK VALUES (‘NETS’, ‘VCR’, 10, 5000, 50000)2) INSERT INTO STOCK(name,item,qty)values(‘abc’,’tv’,100)3) Insert into STOCK select * from SALES

Advanced SQLJoins

A Join is a way to create a Recordset with results from two or more tables based on the relat ionship between them. The different types of joins are

Inner Join - Returns a record only where there are matching records in both tables.

Left Outer Join - Returns a record for every record in the first table, with Nul ls for fields in the second table when there are no matching records.

Right Outer Join - Returns a record for every record in the second table, with Nul ls for fields in the first table where there are no matching records.

Inner JoinsUse the INNER JOIN statement any t ime you want the Recordset to only have a

record when there are matching records in both tables. The query below returns a l ist of books and their publ ishers. I f there is no publ isher l isted for a book, the Recordset wi l l not have a record for that book. Likewise, i f a publ isher has no books, there wi l l not be a record in the Recordset for that publ isher.

E.g. :- Select Name, Tit le From Publ ishers INNER JOIN Tit les ON Publ ishers.PUBID=Tit les.PUBID

Outer JoinsAn Outer join al lows a query to return a record for a table, even i f there is no

matching record in the other member of the join. The different types of Outer joins determine which of the tables always has a record in the Recordset.

The LEFT OUTER JOIN statement always returns at least one record for the first table in the join. I f there are no matching records in the second table, the fields from the second table wi l l be Nul l . The fol lowing query returns a l ist of publ ishers and book t it les. I f a publ isher has no books in the Tit les table, they wi l l have a record in the recordset, but the field of the recordset wi l l be nul l .

E.g. :- Select Name, Tit le From Publ ishers LEFT OUTER JOIN Tit les on Publ ishers.PUBID=Tit les.PUBID

Page 96: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 96

The RIGHT OUTER JOIN statement ensures that there wi l l always be a record for the second table of the join, even i f there is no matching record in the first . The fo l lowing query is s imilar to the previous one; however, this query wi l l return al l t i t les even i f they don’t have a publ isher l isted. I f there is a publ ished with no books, they wi l l not be in the recordset.

E.g. :- Select Name, Tit le From Publ ishers RIGHT OUTER JOIN Tit les on Publ ishers.PUBID=Tit les.PUBID

Nested Joinsi t is possible to nest joins so that many tables can be l inked together in the Recordset. The query below returns a l ist of authors, the books they worked on, and their publ ishers. It starts by joining Authors to Tit leAuthor, then joins that set to Tit les, and Final ly back to Publ ishers.

E.g. :- Select Author, Tit le, Name From Publ ishers INNER JOIN (Tit les INNER JOIN (Authors INNER JOIN Tit leAuthor on Authord.AUID=Tit leAuthors.AUID) ON Tit les. ISBN=Tit leAuthor.ISBN) On Publ ishers.PUBID=Tit les.PUBID

Subqueries

A Subquery is a select statement used as a part of the where clause of another SQL statement. It al lows you to restr ict the results of the main query based on the results of the subquery. The first type of subquery is s imply a comparison between a value and a subquery that returns only one result. The query below retr ieves the name of the publ isher with most expensive book. The subquery finds the maximum price. The main query then gets the publ isher of the book when the book’s price matches the maximum.

Eg:- Select Name From Publ ishers AS P, Tit les AS T where P.PUBID=T.PUBID and T.Price= (Select MAX(Price) From Tit les)

A subquery can be used to compare a value against a whole set of values. The ANY, ALL, SOME statements modify a comparison so that i t appl ies to al l the rows in the subquery. For example, the first query below doesn’t make sense because there would be more than one result of the subquery.

The next query uses ALL statement to perform the comparison between price and al l the results of the subquery. The query returns a l ist of books that cost more than al l the books publ ished by PUBID 45. ALL or SOME could be used to return a l ist of books that cost more than at least one of the books publ ished by PUBID 45. ALL and SOME are equivalent.

E.g. :- Select Tit le from Tit les where Price > ALL (Select Pr ice From Tit les Where PUBID=45)

A subquery may be used to check membership or lack of membership in a group. The IN and NOT IN statements are used to check i f a value is contained in the rewults of the subquery or not

E.g. :- Select Name From Publ ishers Where PUBID IN (Select PUBID From Tit les Where YearPubl ished=2000)

The last type of subquery is used to check whether there are results in the subquery. The EXISTS and NOT EXISTS statements evaluate True or False based on whether there are any records in the subquery. The fol lowing query inserts into the Tit les table only i f that t i t le does not already exist in the table.

E.g. :- Insert into Tit les(Tit le, YearPubl ished, PUBID, ISBN) Select “VB6”, 2000,46,”W123” From Publ ishers Where PUBID=46 and NOT EXISTS ( Select Tit le From Tit les Where Tit le=”VB6”)

Crosstab Queries

Crosstab queries enable you to take results that you normally get using a Group By and pivot them so they are easier to read. A Crosstab query has two parts. The first part, the TRANSFORM statement, specifies what aggregate function to use when populat ing the fields of the recordset. This could be any of the aggregate functions discussed earl ier such as SUM, COUNT, MAX, MIN, AVG etc. The fields in the select statement are the leftmost field of each record, with the aggregate function of the TRANSFORM statement being the r ightmost fields. The second part of the crosstab query is the PIVOT statement, which specifies the column headings that wi l l be appended to the fields in the Select statement. In the Query below, the columns wi l l be the name of the Publ isher fol lowed by the years publ ished. This query shows a l ist of al l publ ishers and a count of the number of books they publ ished in each year.

E.g. :- TRANSFORM Count(*) Select P.Name From Tit les as T, Publ ishers as P where T.PUBID=P.PUBID Group By P.Name PIVOT YearPubl ished IN (1992,1993,1994,1995)

TRANSFORM and PIVOT : - The Transform and Pivot statements are used to create a crosstab query that is easier to read than a standard Group By.

Syntax:- TRANSFORM aggop select PIVOT pivotfield

Page 97: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 97

E.g.:- TRANSFORM sum(Qty) Select Item From Stock Group By Item Pivot Period

DistinctRow Function

The DISTINCTROW function filters dupl icate rows from a recordset. Sometimes when joining between tables, a query may return dupl icate entr ies when al l that’s needed is just one entry. For example, to get each author only once use the DISTINCTROW as below.

1) Select DISTINCTROW Authors.Author From Authors INNER JOIN (Tit les INNER JOIN Tit leAuthor ON Tit les. ISBN=Tit leAuthor. ISBN) ON Authors.AUID=Tit leAuthor.AUID Where Tit les.PUBID=3

2) Select DISTINCTROW Customer.Custname From Customer INNER JOIN Order ON Customer.CustID = Order.CustID

Union Queries

A UNION al lows a SQL query to merge the results of two or more SQL queries into one Recordset and even sort the records over the entire merged Recordset. The query below returns a l ist of publ ishers, authors and the number of books for each. I t then orders the complete l ist a lphabet ical ly .

1) Select I tem, Rate From Stock UNION Select Product As Item, Pr ice As Rate From Item

2) Select Name, As Thing, Count(*) as Tal ly From Publ ishers INNER JOIN Tit les On Publ ishers.PUBID=Tit les.PUBID Group By Name UNION Select Author As Thing, Count(*) As Tal ly From Authors INNER JOIN Tit leAuthor On Authors.AUID=Tit leAuthor.AUID Group By Author, Order By Thing

If there happens to be same item or same author, there wi l l only be one record for each item or author. By using UNION ALL instead of UNION, the query would return al l records, even i f there are dupl icates. In a union query, to match up column names use As statement to a l ias the column names. The only restr ict ion in using Union operator is there must be the same number of columns in each of the queries in the union.

Query Optimization

There are Few things you can keep in mind that wi l l help no matter what p latform you are running on. When bui lding your queries; you should consider the fo l lowing suggest ions to ensure the quickest and most efficient execution of them

Limit the fields returned in a select query to only those you actual ly need Use the Order By c lause on indexed fields Avoid using asterisk (*) as the leading character in pattern matching cr iter ia Structure your queries to return the smallest Recordset possible to meet your

needs When possible, store your queries as QueryDefs in the Database Use comparison operators on indexed fields Crosstab queries work best when column headings are specified using the IN c lause Jo in on Indexed Fields The NOT IN Function is very slow

Page 98: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 98

Chapter 18

RDBMSRDBMS(Relational Database Management System)Relational database is defined as a col lect ion of data indicates relat ion among data elements. i .e., re lational database is a col lection of related data. A database is a collection of sharable information. This definit ion appl ies to al l types of databases.

Relational databases were not the first or the only database design. Other database models are st i l l in use, especial ly for s ingle user databases, but they do not offer the power, flexibi l i ty, and ease of use of relat ional designs.

Databases models include: Hierarchical Network Flat file Relational

The Hierarchical model: I t is based on an ordered tree. The relative order of sub trees is important. Each node in the hierarchy represents a record type. Each l ink represents an association between the two records.

Records in a hierarchical database have a one to many, 1:N relationship

The Network model: Consists of records and l inks between records. The records represent the entity sets. The l inks between the records represent the associat ion between ent ity sets.

Records in a network model have a many to many, N:M relationship.

The flat file model: Is a subset of a relat ional model Consists of one entity Relations must be set up manual ly

A Relational database is a collection of sharable information, defined as tables called relations, that can be operated upon using relational operators

A Relational Database Management System (RDBMS) is a set of data structures and procedures used for the creation and manipulation of relational databases

The rows of a relational table contain the data items or components.

One entire row in a relational database is equivalent to a record.

A Relationship is a correspondence between two entities or elements of an entity about which there is a need to maintain information.

The basic storage structure in a relational database is a table, a two dimensional matrix.Each column in the table represents an attr ibute of the ent ity. Each column has a label, referred to as the column or attr ibute name. The column has a type, referred to as the attr ibute type, which appl ies to a l l the elements in the column. Each element in the column has a value that is derived from the domain of the attr ibute. This is the data item or component. Al l of the data items in a row in the table define an instance of the entity.

A key is an attr ibute that identifies an instance in an entity. A relat ional table may have several keys. One of the keys can be arbitrari ly designated as the Primary key . I t must be unique and have a defined value.

The primary key identifies an instance of a unique entity. Either an employee ID or Social Security Number could serve as a primary key, because they identi fy only one person. When a new instance is added to an entity, the values that define the primary key have to exist and be unique; otherwise, the new instance cannot be added to that ent ity.

Al l ent it ies defined must have a Primary key . Keys that have not been chosen as the primary key are referred to as the alternate keys. For example, a person's name is an alternate key, because it is not necessari ly unique.

A Foreign key is a key (a set of attr ibutes) of an entity, which is the primary key of an associated entity set. Foreign keys are used to establ ish a relationship between entit ies. They are needed to provide navigat ion between associated ent it ies.

Indexes are special objects for searching through the contents of the tables in the database. An index consists of a key and row number pair. Indexes al low for quick access

Page 99: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 99

to the contents of a row in a table. There can be many indexes defined for a particular table. The index determines the order in which records are sorted. For example, the index for the table on the left is employee ID. The employee IDs are sorted in numerical order. The one on the r ight is sorted in numerical order by Social Security Number.

Some RDBMSs al low the creation of Sequences.

A Sequence is a series of unique numbers created for a particular table. The start ing point for the sequence can be specified when the sequence of the table is defined.

Sequence numbers can be used by appl icat ions that require unique numbers, such as invoice numbers. I f a database does not al low the creation of sequences, then the appl ication programmer wi l l have to use another method

Data access is a service of a database manager, which al lows data to be retr ieved from disk drives, without writ ing routines to retr ieve the data. The logical path to the data is cal led the access plan. When an appl ication is pre-compiled, the access plan that optimizes performance is stored, either in the database or in a file cal led a bind file.

When the appl ication is executed, the access plan is used to retr ieve the data.

A Synonym is an alternate name (al ias) of a database object. Synonyms are used to s impli fy references and provide security. Users do not need to be aware of the detai ls of an object. They can refer to the object by its synonym. The synonym can be useful when the real database object is located on a remote machine.

A View is a virtual table that can be accessed l ike a normal table. This virtual table does not exist in the database, but the definit ion of the virtual table does. The contents of the view are dynamical ly obtained from the tables for which the view is defined. A View al lows a filtered look at tables.Views are often used to l imit access to the contents of the original table. A View can be used to l imit the abi l i ty to manipulate the data in a table to a predefined subset of the table. Views provide an extra measure of security.

There are two types of data in a database:

User defined data System generated data

The System data is data about tables, views, and indexes that is created on behalf of the user.

The information kept about the system data is referred to as the data dict ionary.

The dict ionary concept has been extended to include data about data.

A database management system enables roles, authorizations, and privi leges to be assigned to users. A user has to be defined to the database prior to being able to use the services of the database management system.

The Schema is a summary or global view of a s ingle database. I t contains the tables, views, and indexes of the database. The schema records:

All the logical units of data The relationships that exist between these units of data The type of data

The Schema may also provide information about security and access r ights to data.

A Database Management System consists of a set of tables used by the system to administer al l the database objects that are defined.

Some typical examples are: Tables to maintain user IDs and passwords Table for p lans Table for table names Table for indexes Table for v iews Table for sequences

Before looking at the relational database design process, consider some of the roles of the personnel involved in the design, development, and management of a database.

They include: System Programmers Database Administrators Data Modelers Application Developers Application Users Security Administrators

A system programmer's role is to instal l the database management system software on the system.

The system programmers responsibi l i t ies include:

Page 100: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 100

Instal l ing newer releases of the database system software Planning the physical resources required by the system (e.g. , disk space) Configuring the system for optimal performance

The database administrator (DBA) is responsible for creating and maintaining appl ication databases. In some organizations, the DBA role is combined with the system programmer role.

The DBA responsib i l i t ies include: Working with the data modeler to transform the logical data model into a physical

model Working with the appl icat ion programmer to determine access paths and identi fy

necessary indexes Creating the physical database objects (e.g., tables, indexes, and constraints) De-normalizing attr ibutes in order to improve performance Providing guidance to appl icat ion programmers with respect to optimal database

access Creating backup and recovery jobs

The role of the data modeler is to analyze the business data requirements and create a logical data model. This involves determining the entit ies, their attr ibutes, and the relat ionships between the ent it ies.

The data modeler responsibi l i t ies include: Working with the business users and appl ication developers to understand the data

requirements Creating an entity relationship diagram Gathering definit ions for a l l attr ibutes Determining the candidates for primary keys Verify ing that the model satisfies the requirements Gathering information on data volumes Working with the DBA to turn the logical data model into a physical model

The appl ication developer's role is to turn business specifications into appl ication processes for the appl ication users.

The appl ication developer's responsibi l i ty includes: Turning business specifications into appl ication code Testing code to remove al l bugs Ensuring that the database navigat ion is coded in an optimal manner Moving the code to production

Appl icat ion users run the appl ications that are created on their behalf , to make day-to-day business decis ions or to store information for future decis ions.

Appl icat ions users' responsibi l i t ies include: Providing the business specifications for the appl ications Ensuring that the developed appl icat ions meet the specified business requirements Running the appl icat ion in the business environment

The security administrator grants database access privi leges to individual users or groups of users of a database. Typical ly , in a test or development environment, the database administrator or appl icat ion development team handles this function, but the security group more often handles security for the production system.

Data modeling

Designing databases is a large and complex field. In most large organizations, there are teams of people who do this job.

This is a very brief introduction intended to describe the major steps involved in designing a database:

Designing the logical data model Transforming the logical data model to a relational (physical) database model

The first step in the logical design process is to bui ld a conceptual model of the database.

This wi l l include decisions l ike: What data to include in the database The characterist ics of that data The relationships among the data What events affect that data How to make the data avai lable to users

The design process wi l l be to bui ld a logical data model of this concept.

Logical design (data model ing exercise) is an iterat ive exercise which includes the fo l lowing steps:

1. Identi fy entit ies 2. Determine relationships between the entit ies, including the foreign keys 3. Determine entity properties; these are the key attr ibutes of the entity

Page 101: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 101

4. Identi fy the primary business rules and events that have an affect on entit ies and relat ionships

5. Identi fy al l the attr ibutes of the ent ity 6. Normalize the logical model

The steps involved in identi fying the entit ies are: 1. Interview the users (cl ients of the system) 2. Identi fy the major data items that cl ients want included in the database 3. Identi fy the entit ies 4. Rat ional ize the entit ies into sets

The propert ies of entit ies should be defined as fol lows: Choose a primary key for the ent ity Identi fy the foreign keys for the entity Identi fy alternate keys for the entity

Primary business rules govern the properties and behavior of the data of the particular database being designed. An example is the range of numbers that are val id for employee ID numbers in a given company. Defining these rules is an ongoing process. Although these rules may change, some init ial rules of business must be defined for the purposes of model ing data for the database design.

The integrity rule is designed to make certain that a l l data entered in the database is val id. The integrity rule refers to the primary keys of an entity:

The Integrity rule for primary keys is: "Each primary key must exist and be unique."

Other rules that have to be defined are: 1. Insert rules - what const itutes a val id insertion. 2. Delete rules - what contitutes a val id delet ion.

The Referential integrity rule appl ies to foreign keys.

The rule is: "If an entity has a foreign key, then the foreign key must either match the value in the table for which it is a primary key, or it must be null."

Referential integrity requires that insert, delete, and update operations maintain these reference paths.

Constraints provide boundaries on the data that is entered into tables as an insert or update. The constraints set the domain of the attr ibute. Some database management systems provide a mechanism for sett ing constraints.

In some systems, i t is left up to the appl ication writers to provide edit checks in order to ensure that the attr ibute value being set is part of the domain of the attr ibute. Constraints also define the rules for insert ing, updating and delet ing data. These are the primary business rules of any database.

There are six insert rules: 1. Dependent: a chi ld entity can be inserted, i f a parent entity exists 2. Automatic: when inserting a chi ld ent ity, i f a parent does not exist, create one 3. Nul l i fy: insert chi ld, set foreign key to nul l , i f the parent does not exist 4. Default : insert chi ld, i f parent does not exist, set the foreign to a default value 5. Customized: insert chi ld provided it meets defined insertion cr iter ia 6. No Effect: insert chi ld uncondit ional ly

There are six delete rules: 1. Restr ict : delete parent, i f there is no chi ld 2. Cascade: delete the parent and cascade the deletion to al l chi ldren 3. Nul l i fy: delete the parent and set the chi ld's foreign key to nul l 4. Default : delete the parent and set the foreign key of the chi ld to a default value 5. Customized: delete the parent, i f predefined condit ions are met 6. No Effect: delete the parent uncondit ional ly

Al l the non-key attr ibutes and their types have to be ident ified as part of the design process. Derived data are attr ibutes that are derived algorithmical ly . These should be indicated as derived.Entit ies with the same primary key should be combined into one entity.

The next step in the data model ing process is to normalize the relationships.

Normalization is simplification . The objective is to remove redundant information and relat ionships. The goal is to reduce al l N:M relationships to 1:N. To do this, new entit ies must be created.

The advantages of a normalized design are: The amount of storage space required is minimized because redundant attr ibutes

are removed. Data inconsistency is reduced, because the attr ibutes are stored only once.

Page 102: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 102

Delete and update operat ions are against a s ingle attr ibute instead of mult iple copies of the same attr ibute.

The stages in the normalization process are: 1. First Normal Form 2. Second Normal Form 3. Third Normal Form

The third normal form is usual ly adequate to ensure a correct and consistent logical data model with al l redundancies removed.

An ent ity is in First Normal Form, i f i t does not have any repeating groups.

Each attr ibute is atomic and has a unique meaning.

The entity is put into first normal form by moving any repeat ing group to a new entity.

An ent ity set is in Second Normal Form when the non-key attr ibutes of an ent ity in First Normal Form are whol ly dependent on the entire primary key.

Remember, a primary key is the minimal set of attr ibutes that uniquely identifies an instance in an entity.

In the Second Normal Form, the non-key attr ibutes can depend on other non-key attr ibutes, as wel l as the primary key.

An ent ity is in Third Normal Form, i f i t is in Second Normal Form, and the non-key attr ibutes depend on the primary key (as in the Second Normal Form) and only the primary key (or alternate key). In this form, the non-key attr ibutes cannot depend on other non-key attr ibutes.

Once the logical model is defined, the next step in relational database design is transforming a logical database model into a relat ional (physical) database.

Relational (Physical) model

The steps to transform the logical model to a physical model are: 1. Identi fy the tables 2. Identi fy the attr ibutes and their types 3. Create the tables using the database manager 4. Define and create the business rules about the entit ies 5. Design the rules for associations (relationships between ent it ies) 6. Design the rule for individual attr ibutes 7. Tune for performance by defining indexes 8. De-normalize i f required to increase performance

The three major languages used to create and maintain databases are: 1. Data Storage Language (DSL) 2. Data Definit ion Language (DDL) 3. Data Manipulat ion Language (DML)

The Data Storage Language (DSL) is used for defining the physical storage of the database. The planning of physical storage is important in database design, because the size and location of the disk storage space must be defined, before the database is placed there. Furthermore, databases grow and shrink continual ly. So planning how they wi l l be mapped to physical storage is crucial to their successful operation.

The physical storage definit ion specifies: The storage medium and individual drives The physical ordering for the data The placement of data The retr ieval amount (buffer sizes) The logical to physical mapping of data

The Data Definit ion Language (DDL) is used to define and create tables, v iews, and other database objects.

The DDL is a self contained language that provides the abi l i ty to: Specify the relational data model Name the logical units of the database Describe the relationships and associations Specify the domain of values for indiv idual attr ibutes Specify the data types for attr ibutes Specify the keys for ent it ies {tables} Specify integrity constraints on the data Specify the access rules for data

The Data Manipulat ion Language (DML) is used to maintain user's data. This defines the type of operat ions that a user can perform on the data. The types of operations that can be performed on tables are based on "relations algebra" (derived from set theory) and are referred to as relat ional operators.

The relational operators are:

Page 103: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 103

Restr ict ion {Selection} Projection Cross-Product Jo in Union Intersection Divis ion Difference

Restr ict ion and projection are appl ied against a s ingle set. Cross product, join, d ivis ion, union, intersect ion, and difference are appl ied against two sets. Restr ict ion is used to l imit the number of rows retr ieved to a subset of the data in the table based on some condit ions. The Restr ict ion is del imited by one or more condit ional operators appl ied against the attr ibutes of the table. Al l of the attr ibutes of the set that meet the restr ict ion condit ion wi l l be selected.

The condit ional operators are: Equal to Less than Less than or equal to Greater than Greater than or equal to Not equal to

These are used to apply condit ions to a restr ict ion operation.

Projection is used to produce a new set comprised of only some of the attr ibutes of the original set.

Only the specified attr ibutes are selected and al l dupl icates are removed.

The cross product of two sets is a set whose contents are al l the combinations of the first two sets.

The number of rows in the third set is the product of the number of rows in the first set and the number of rows in the second set.

The join operation creates a new relation from a set of relat ions, where the new relation is based on relational operators between compatible attr ibutes in the tables specified for the join.

The join is used to select information that is found in two or more relat ions.

The attr ibutes that are used to join these relat ions have to be compatib le (of the same data type).

The union of two sets is a set with elements of both sets included and the dupl icates removed.

Both sets should have the same number and type of attr ibutes: 1. The tables must have the same number of columns 2. The columns have to be of the same type 3. The order in which these column types have been set up must be the same (they

have the same "shape")

The intersection of two or more sets is a new set, which contains al l the elements that exist in al l of the intersected sets. This means the intersection of tables wi l l contain al l the columns which are in al l the specified tables. These columns have the same data type and possibly the same values.

The divis ion operat ion wi l l result in a relat ion containing columns from the "dividend relat ion" for which there are matching column values corresponding to every row in the "div ider relation".

The difference of two sets is a set of a l l the rows in one set that are not in the other.

Stated differently, the difference is the rows in table A with al l the rows that are also in table B removed.

The two tables must have the same "shape".

The order of the sets is important.

I f the order of the difference from the previous example were reversed, the resultant set would change.

In order to bui ld a col lection of related data, you need three key bui lding blocks. They are,

a) Data Fields : - the first bui ld ing block in relat ional database is a data field. I t contains the smallest element of data that you can store in a database and each field contains only one data element. E.g. :- to store the name of customer, you must create a data field some where in the database and also give a fieldname such as CustomerName and i f you want to store

Page 104: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 104

the balance of a customer, you must create another field such as balance and al l the fields you create are shared in a s ingle database.Note:- a Data field is also known as Data Column

b) Data Records : - Data records are col lection of related data fields. E.g. :- Customer_name, Amount_due,Address wi l l be in a table. Al l these fields of a s ingle customer record describes a data record.

Note : - a Data record is also known as data row.A single data record contains only one copy of each defined data field. I .e., a

s ingle data record contains more than one customer name.

c) Data Table : - By comparing data fields and data records you create the most common element of a relat ional database datatable. A table contains mult iple data records and each record contains mult iple datafields.

Database relationship:-A database can contain several related table using relationship is a very efficient way to store very complex data.

E.g. :- Table storing CustomerName could be related to another table sharing the sales information of the customer. By establ ishing meaningful relat ionship between datatables you can create flexible data structure that are easy to maintain. You establ ished a relat ionship between datatables by using pointer or qual ifier fields in your data tables. You are qual ifier fields to point two records in other tables that have addit ional information. Qual ifier field usual ly described one to one relationship. You use pointer field to point one or more records in other tables that have related information. Pointer field usual ly defined one-to-many relationship.

One to one relationship:-One to one relationship are used to l ink records in a master table to s ingle record in another table.E.g. :- I f you have two tables, one containing the address information of customers and other table contains the due amount of customers. By creat ing a common field in both table (say code) you can l ink the information in both tables.

One to many relationship:-One to many relationships are used to l ink records in a master table to mult ip le records in another table.

E.g. :- I f you have two tables, one containing customer address information and other contains sales detai ls of customers. The sales detai ls table can have more than one record for a single customer. Here also you need to specify a common field in both tables.

Note : - At least one datafield in each table acts as keyfield

Key fields in relational database are used to define and maintain database integrity and to establ ish relationship between datatables. You create keys in your table by designing one or more fields in your table either as a primary key or as a foreign key. A datatable can have one primary key, but i t can have several foreign keys.

The primary key is used to control the order in which the data is display. The foreign key is used to relate to fields in another table in the database.Keyfields are also known as index fields. A col lection of records-that is , rows of records where each column is a field becomes a table. So a database can be defined as col lection of one or more tables. In DAO, those col lections are cal led the workspace, and in RDO and ADO, they are referred as the data environment. You can also have indices in databases, and those are pointers to specific fields, either in the current database or another one.

Page 105: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 105

Chapter 19

Introduction to Data AccessAll appl ications use structured information of one kind or another. Data access in Microsoft Visual Basic gives you the tools to create and use structured database systems to manage your appl ication's data.These tools include the Microsoft Jet database engine, the Data control , and the data access objects (DAO) programming interface.Using data access objects, you can create databases and bui ld ful l - featured appl ications that access exist ing databases in many popular formats, including Microsoft Access, Bereave, dBase, Microsoft FoxPro, and Paradox, as wel l as Open Database Connectiv ity (ODBC) c l ient/server databases l ike Microsoft SQL Server.The abi l i ty to create and access structured database systems gives you many programming advantages:

· It lets you write programs that use exist ing databases.· It al lows your appl ication to share data with other programs.· It s implifies your programming, s ince you do not need to handle low-level file

accessing and searching.

Data Access Object (DAO)When VISUAL BASIC first started working with databases, i t used the Microsoft Jet Database Engine, which is what Microsoft Access uses. Using the Jet Engine represented a considerable advance for VISUAL BASIC, because now you could work with a l l kinds of data formats in the fields of a database: text, numbers, integers, longs, s ingles, doubles, dates, binary values, OLE objects, currency values, Boolean values, and even memo objects. The Jet Engine also supports SQL, which database programmers found attractive. To support the Jet Database Engine, Microsoft added the data control to VISUAL BASIC, and you can use that control to open Jet database (.mdb) files. Microsoft a lso added a set of Data Access Objects (DAO) to VISUAL BASIC.

DBEngine - The Jet Database EngineWorkSpace - An area can hold one or more databasesDatabase - A col lect ion of tablesTableDef - The Definit ion of a TableQueryDef - The Definit ion of a QueryRecordset - The set of records that make up the result of a queryField - A Column in a TableIndex - An ordered l ist of recordsRelation - Stored information about specific relat ionship between tables

Visual Basic provides two methods of interfacing with the Jet database engine: the Data control and data access objects. The Data control gives you l imited abi l i ty to access exist ing databases without programming; the DAO model is a complete programming interface that gives you total control of the database. These two methods are not mutual ly exclusive; in fact, there are many situations where you wi l l want to use both of them together.

The DAO model is a col lection of object classes that model the structure of a relational database system. They provide properties and methods that al low you to accomplish al l of the operations necessary to manage such a system, including faci l i t ies for creat ing databases, defining tables, fields and indexes, establ ishing relations between tables, navigating and querying the database, and so on.

The Jet database engine translates these operations on data access objects into physical operations on the database files themselves, handl ing al l the mechanics of interfacing with the different supported databases.

Database programming in Visual Basic consists of creating data access objects, such as Database, Table Def, Fie ld, and Index objects, that correspond to the various parts of the physical database you want to access. You use the properties and methods of these objects to perform operations on the database. You can display the results of these operations and accept input from the user on Visual Basic forms, using both bound and unbound controls. This approach simplifies the code you need to write and insulates you from the underly ing structure and mechanics of retr ieving and updating data. I t gives you great flexibi l i ty , because you can use the same objects, properties, and methods to work with a wide variety of supported database formats. Also, i f you change from one database format to another (for example, port ing a local Microsoft Access database to a SQL Server database on a network) , you' l l need to make few changes in your code to accommodate the change. You can even create appl ications that join tables from two or more different databases in a s ingle query or report.

There are three categories of databases that Visual Basic recognizes through DAO and the Jet engine:

Page 106: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 106

Visual Basic DatabasesAlso cal led native databases, these database files use the same format as Microsoft Access. These databases are created and manipulated directly by the Jet engine and provide maximum flexibi l i ty and speed.

External DatabasesThese are Indexed Sequent ial Access Method ( ISAM) databases in several popular formats, including Btr ieve, dBASE I I I , dBASE IV, Microsoft FoxPro versions 2.0 and 2.5, and Paradox versions 3.x and 4.0. You can create or manipulate a l l of these database formats in Visual Basic. You can also access text file databases and Microsoft Excel or Lotus 1-2-3 worksheets.

ODBC DatabasesThese include cl ient-server databases that conform to the ODBC standard, such as Microsoft SQL Server. To create true cl ient-server appl ications in Visual Basic, you can use ODBC Direct to pass commands direct ly to the external server for processing.

VISUAL BASIC Database field type:-VISUAL BASIC stores values in the database in datafields. VISUAL BASIC recognizes

14 different types of fields that you can use to store values. Each datafield has unique qual it ies that make it special .

Type Size VISUAL BASIC Type Comments

Binary V none l imited to 255 bytes

Boolean 1 Boolean stores 0 or 1 only

Byte 1 integer 0-255

Counter 8 long auto incrementing long type

Currency 8 currency 15 spaces left to decimal 4 to r ight

Date-t ime 8 Date/Time date stores on left and t ime on r ight

Double 8 double -- -- -- -- -- -- -

Guide 16 none global ly unique identifier

Integer 2 integer -- -- -- -- -- -

Long 8 long ---- -- -- -- -- -

Long binary memo --- none for OLE object

Memo ---- str ing up to 1.2 GB

Single 4 single -- -- -- -- -

Text X str ing length l imited to 255

The first column contains the VISUAL BASIC datafield type name.The second column shows the number of bytes of storage taken by various datafield type. I f the size is set to a/b, the length is determined by you, at design t ime or run t ime.The third column shows the equivalent VISUAL BASIC data type for associated database field t ime.

The Data ControlThe data control enables you to move around in a database from record to record and to display and manipulate data from the records in bound controls. This control displays a set of arrow buttons the user can cl ick to move through the database, and the records from that database are displayed in bound controls. In fact, you can perform most data access operations using the data control without writ ing any code. Data-bound controls automatical ly display data from one or more fields for the current record, and the Data control performs al l operations on the current record. I f the data control is made to move to a d ifferent record, a l l bound controls automatical ly pass any changed to the data control to be saved in the database. The data control then moves to the requested record and passes back data from the current record to the bound control ’s where it ’s displayed.

When an appl ication begins, VISUAL BASIC uses data control properties to open a selected database, create a DAO database object, and create a Recordset object . The Data control ’s Database and Recordset properties refer to those Database and Recordset object, and you can manipulate the data using those propert ies. For example, i f you have an SQL statement to execute, you place that statement in the data control ’s RecordSource property, and the result appears in the Recordset property.

Page 107: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 107

Adding a Data Control to a ProgramThe data control is the only intr insic database control already in the toolbox. You can double c l ick on it to add to the form. Set the controls caption property as you desire.

Opening a Database with Data controlTo connect a data control to a database, you just set the data control ’s DatabaseName property to the path and name of the Access/ Jet database file you want to open. In addit ion, you select the table you want to work with in that file with data control ’s RecordSource property. After connect ing the databasename property, you’ l l get the l ist of tables / queries in that database in RecordSource property. Select one you want to connect.

Connecting a Data Control to a Bound ControlTo see the data in data control , we’l l use a data-bound control-a text box. To connect a text box to a Data Control , set the textbox’s DataSource property to the name of the Data Control . To display a particular field in the textbox, p lace the field’s name in DataField property. When you move through the database using data control ’s moving buttons, the current records data wi l l be displayed in text box.

Page 108: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 108

Chapter 20

Remote Data Object (RDO)RDO ( Remote Data Objects )Remote Data Objects(RDO) connect to databases using ODBC (Open DataBase Connectivity). You set up ODBC connections to databases using the ODBC item in the Windows Control Panel, and then use one of those connections with RDO objects. The Remote Data Objects are designed in paral le l with the Data Access Objects; for example, the database engine is rdoEngine instead of DBEngine, Recordsets have become rdoResultsets, TableDefs became rdoTables, Workspaces became rdoEnvironments, F ield objects became rdoColumn Objects, and so on. Although the names have changed, the command set is very similar to DAO.

The Remote Data ControlLike the data control , the remote data control gives you access to a database and displays data in bound controls. Unl ike the data control , however, you use the remote data control to accss ODBC data sources. As with the Data Control , i f the remote data control is instructed to move to a different row, al l bound controls automatical ly pass any changes to the remote data control to be saved to the ODBC data source. The remote data control then moves to the requested row and passes back data from the current row to the bound controls where it ’s d isplayed. In fact , the remote data control behaves l ike the data control in most respects, with some differences; for example, you can treat the remote data control ’s SQL property l ike the data control ’s RecordSource property, but i t cannot accept the name of a table by itself unless you populate the rdoTables col lection first .

Remote Data objects and col lections provide a framework for using code to create and manipulate components of a remote ODBC database system. The Remote Data Object (RDO) is used for accessing RDBMS databases over local area network. The RDO and RDC ( Remote Data Control ) models properties and methods make them better suited to manipulating data in remote systems. The RDC and RDO models are shipped as part of VISUAL BASIC Enterprise edit ion. One of the most obvious differences is in the size of the object models. The DAO model has over twenty major objects to work with, and the RDO model has less than fifteen. This reflects the fundamental differences between the models. The RDO model is designed to al low access only to the data , where as DAO model is designed give complete access to both data and structure of table. RDO interface was meant for use when connecting to large mult i -user database systems l ike SQL server, ORACLE, etc.

Registering an ODBC sourceI t is , with the Remote Data Control , you can use an ODBC data source with a remote data control . But first, you have to configure a new connection for the ODBC source. You configure an ODBC connection with the 32-bit ODBC item in Windows Control Panel. Open that i tem, c l ick the System DSN tab (DSN stands for Data Source Name), and cl ick the Add button to open the Create New Data Source dialog box. You can see the ODBC drivers instal led on your system in this dialog box. Select the one you want to use and cl ick finish. For example, to use a Microsoft Access Database, we’ l l select the Microsoft Access Driver entry here. This opens the ODBC Microsoft Access Dialogbox. Use the Select Button to select the database file you want to connect with this DSN, give a name for DSN in Data Source Name box, say “abc” and cl ick OK. This creates a new ODBC connection for our file, and that connection appears in the ODBC Data Source Administrator. Cl ick OK to c lose the ODBC Data Source Administrator. Now you’ve added a new ODBC source to your computer’s data environment. we’ l l use this DSN to connect with this Database.

Opening a Database with Remote Data ControlTo add a new remote data control to a form, fol low these steps.

Select the Project>Components Click the Controls tab in the Components dialog Select the Microsoft Remote Data Control entry in the Controls l ist box Click OK to c lose the Components Dialog This adds the Remote Data Control to your Toolbox, draw that control on your form Connect the remote data control to an ODBC data source with the DataSource

property. Create a result set that you can work with by supplying an SQL statement in the

SQL property.

Let’s see an example, Add a Remote Data Control , MSRDC1, to a form now. Set the remote data control ’s DataSourceName property to “abc” which we’ve just created.Unl ike the data control , you need to create a result set to work with the remote data control , and we create a result set by select ing the entire students table with SQL statement for example “SELECT * FROM STOCK” (Where Stock is a Table in the database). P lace that str ing in the control ’s SQL property.

Page 109: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 109

Connecting a Remote Data Control to a Bound ControlTo connect a text box to a remote data control , set the text box’s DataSource property to the name of the remote data control . To display a particular field in the text box, place that field name in text box’s DataField property.

Let ’s see an example, here we wi l l use the database we created and the remote data control we’ve created. Add a text box, Text1, to the form, and set i ts DataSource property to remote data control , MSRDC1. When you move through the database with the data control , the remote data control wi l l hold the current record; to display a field in the current record, place that field’s name in the text box’s DataField property.

The Basics of RDO

By default, al l remote connections to data are nonupdatabale (readonly) datasets. You can change this behaviors by manipulating the fol lowing three properties

Cursor Drivers : - Used to define the way in which you can move within a set of data. The database engine must keep track of al l records in the col lect ion and their place in the dataset. This process of keeping track of the location of data pointer in dataset is cal led cursor management. You can use two primary locations to keep track of cursor location : the c l ient workstation or the database server. Under RDC and RDO models, the ODBC driver handles the local workstation version of cursor management. The database server that holds the data handles the server-side cursor management.

Under RDO there are two other possib le sett ings for cursor management. Cl ient Batch and None. You can use the Cl ient Batch option with advances data servers that a l low mult iple data requests to be sent s imultaneously over the same connect ion. In this case you can batch up mult iple SQL statements in a s ingle str ing and send them to the server at one t ime. The server manages the requests and reports results back to you as each SQL statement is completed.

You also can choose to use no cursor driver when accessing remote data. This results in the server sending you a single record from the dataset each t ime you request i t . You can not request previous records from the server and, i f you want to start at the top of the col lection, you must restart the query. This is the most l imited cursor management avai lable for remote connection.

Cursor driver options with RDO and RDC

Option integer value description

rdUSeIfNeeded 0 Instructs RDO to determine the best cursor driver. This is the default sett ing

rdUseOdbc 1 Instructs RDO to use cl ient s ide ODBC cursor

driver to keep track of datapointer in the dataset

rdUseServer 2 Instructs RDO to use the remote RDBMS cursor driver to keep track of the datapointer in the dataset

rdUseCl ientBatch 3 Instructs RDO to use the remote RDBMS to manage mult iple cursors in response to batch requests sent from the c l ient workstation. This is avai lable only on advanced RDBMS systems (SQL server 6.0 and higher)

rdUseNone 4 Instructs RDO to use no cursor driver. The result is a return on only one row, no

matter how many rows are in the result set. This option st i l l can be used to perform action queries such as UPDATE SET, INSERT INTO, SELECT INTO, etc.

When rdUseIfNeeded is in place, RDO wil l attempt to use server s ide cursors i f they are avai lable. I f the RDBMS does not support server s ide cursor management, RDO wil l use the cl ient workstation cursor manager(rdUseOdbc). The rdUseNone option is used only i f the value is expl icit ly selected.

The important thing to remember about cursor drivers is that they govern the way you can navigate the dataset. The other important aspect of cursor driver is that, with RDO, you can select the driver you prefer: Cl ient Side or Server Side and data source (RDBMS) must support your cursor request in order for you to be able to select certain server s ide options.

Page 110: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 110

Dataset Type:- Several types of datasets can be returned by the remote data source.

Dataset Type Options with RDO

Option Integer Value Description

rdOpenForwardOnly 0 Creates a read-only, scrol l forward only dataset. Al l members are copied to the workstation for use. This is the default option

rdOpenStatic 1 Creates an updatable data set that hasnonchanging membership. New records added to the set may or may not appear as part of the set, depending on the cursor driver. Al l members are copied to c l ient workstation for use.

rdOpenDynamic 2 Creates an updatabale dataset that has changing membership. New records added

to the set wi l l appear as part of the set . Actual datarecords are buffered to the cl ient workstation as needed. Record keys are not used

rdOpenKeyset 3 Creates an updatabale dataset that has

changing membership. New records added to the set wi l l appear as part of the set . Actual records are buffered to the c l ient workstation as needed record keys are created to point to al l members of the set. This enables you to use bookmarks with the dataset.

The primary work of dataset management from the workstation point of view is gaining access to the actual rows of data stored in the remote system. The most efficient method for gaining access is to receive a set of row pointers from the RDBMS, not to actual ly receive the complete rows of data. In this way, the RDBMS can al low mult ip le users to have access to the same set of records without having to deal with major synchronization work i f more than one user attempts to update the same row of data. For this reason, RDO supports the use of rdOpenKeyset datasets. These are sets of data that contain not just data rows, but also key set pointers to other rows in the requested dataset. RdOpenKeysets are the remote data access version of Microsoft Jet Dynaset type datasets.

The rdOpenDynamic datasets do not support keys, but they do act as dynamical ly changing set of data. These dynamic datasets reflect newly added or deleted records just as rdOpenKeyset datasets, but they do not support the use of bookmarks. This is because the rdOpenDynamic datasets are kept dynamic through the use of recurr ing refreshes of the data membership from the remote data source. Although this method is accurate, i t is hardly efficient. I f you have large sets of data, using the rdOpenDynamic option can result in decreased throughput, because al l data members are shipped to the c l ient each t ime the set is refreshed.

It is also important to note that rdOpenStatic datasets are updatable. Even though their membership is kept static , i t is st i l l possible to update the records in the set. These datasets act much l ike an updatabale version of Microsoft Jet Snapshot dataset.

Page 111: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 111

Chapter 21ActiveX Data Object (ADO)

ADO (ActiveX Data Objects)ActiveX Data Object(ADO) model is designed to enable access to databases over internet connections. Microsoft’s latest set of data access objects are ActiveX Data Objects. These objects lets you access data in a database server through any OLEDB provider. ADO is intended to give you a consistent interface for working with a wide variety of data sources, from text files to ODBC relational databases to complex groups of databases. The way Microsoft implements connect ions to al l those data sources is with the OLE DB set of COM interfaces, but that standard is a very complex one. Our interface to that interface, so to speak, is ADO, a set of objects with properties, events, and methods.

Connection-access from your appl icat ion to a data source is through a connect ion, the environment necessary for exchanging data. The connection object is used to specify a part icular data provider and any parameters.

Command-a command issued across an establ ished connection manipulates the data source in some way. The command object lets ADO make it easy to issue commands.

Parameter-Commands can require parameters that can be set before you issue the command. For example, i f you require a debit from a charge account, you would specify the amount of money to be debited as a parameter in a parameter object.

Recordset-I f your command is a query that returns data as rows information in a table, then those rows are placed in local storage in a Recordset object.

Field-A row of a Recordset consists of one or more fields, which are stored in Field objects.

Error-Errors can occur when your program is not able to establ ish a connection, execute a command, or perform an operation, and ADO supports an Error object to hold the result ing Error.

Collection-ADO provides col lections, an object that contains other objects of a particular type. ADO provides four types of col lections: the Connect ion object has the Errors Col lection, the Command object has the Parameters col lect ion, the Recordset object has the Fields col lection, and the Connection, Command, Recordset, and Field objects al l have a Propert ies col lection, which contains a l l the property objects that apply to them.

Events-ADO uses the events, just l ike other interface objects in VISUAL BASIC. You use event handl ing procedure with events. There are two types of events: Connection Events, issued when transactions occur, or when commands are executed, or when connections start or end and RecordSetEvents, events used to report the progress of data changes.

ADO also includes Remote Data Services (RDS), with which you can move data from a server to a c l ient appl ication or Web Page, manipulate the data on the cl ient, and return updates to the server in one round-tr ip.

The ADO Data ControlThe ADO data control is s imilar to the data control and the remote data control . The ADO data control is designed to create a connection to a database using Microsoft ActiveX Data Objects (ADO). At design t ime, you create a connection by sett ing the ConnectionStr ing property to a val id connection str ing, then set the RecordSource property to a statement appropriate to the database manager.

You can also set the Connect ionStr ing property to the name of a file that defines a connection (the file is generated by a Data Link Dialog box, which appears when you cl ick ConnectionStr ing on the Properties window and then cl ick either Bui ld or Select). You then connect the ADO data control to a data bound control such as the data grid, data combo, or data l ist control by sett ing its DataSource propert ies to the ADO data control .

At runtime, you can set the Provider, ConnectionStr ing, and RecordSource properties to change the database.

Opening a Database with an ADO Data ControlTo add a new ADO Data control to a form,

Select Project > Components Click the Controls tab in the Component Dialog box Select the Microsoft ADO Data Control entry Click OK to c lose the components dia log box This adds the ADO data control tool to the toolbox, draw that control as you

want i t on your form Connect the ADO data control ’s Connection object to a data source with the

ConnectionStr ing property, separating items in that str ing with semicolons. At the least, you should specify the Provider (the type of OLE DB) and Data Source (data base name) values in the ConnectionStr ing.

For Example, here, we’l l connect an ADO data control to the database to an Access Database. To document that, add an ADO data control , Adodc1, to a form, set i ts ConnectionStr ing property to specify the data provider type and the data source for that database l ike this

“PROVIDER=Microsoft.Jet.OLEDB.3.51;Data Source=C:\ABC\MAIN.MDB;”

Page 112: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 112

Connecting an ADO Data Control to a Bound ControlTo connect a textbox to an ADO data control , set the text box’s DataSource property to the name of the ADO data control . To display a particular field in the text box, place that field’s name in the text box’s DataField property.

The Data Form Wizard: Creating a Data FormYou can use the VISUAL BASIC Data From wizard to create a form using ADO control or ADO code that lets you open and edit a database. To use the Data Form wizard, select i t in the VISUAL BASIC Add-Ins menu and fol low the steps in the Data Form wizard, one step for each successive window that appears in the wizard.

Introduct ion Window. This window asks i f you want to load a profile to create the data form . Cl ick Next

Database Type. This window lets you select the database format, l ike Microsoft Access or ODBC. For the example select Access

Database. This window lets you select the database to work with. Use the name box and the browse button to select your database or data source. The data form wizard wi l l create the correct connection str ing for the ADO data control . Cl ick Next

Form. This window lets you specify the name of the form you’re creating, as wel l as the form layout. Single record, grid, and so on. You can also specify how to bind the database to the form: with an ADO control or ADO code, or with class. Choose ADO control for binding. Cl ick Next to continue

Record Source. In this window, select the table name and the fields you want displayed. Cl ick next to continue

Control Selection. Specify the buttons you want in the data entry form. Add, Delete, Refresh, and so on. Leave al l options selected and Cl ick Next

Finished!. Cl ick Finish button to create the new data form

Page 113: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 113

Chapter 22

Using Database Control Methods:Adding, Deleting and Modifying Records

Like most controls, the DAO, RDO and ADO controls have methods, events and properties. To make these controls consistent, Microsoft has given them the same core methods, and we’l l take a look at those methods here. Using these methods, users can add records to a database, change those records, delete them, and move around in the database.

Because al l data controls have the same core methods, we’ l l use a data control , Data1 in this example. Add two text boxes and command buttons Add, Delete, Refresh, Update, Next, Previous, , First and Last .

Adding Records to DatabasesYou can add a new record to a database with the AddNew method of the Recordset property of a Data or ADO control , or of the Resultset property of a Remote Data control . In this example, when the user c l icks Add button, we can add new records.

Private Sub cmdAdd_Cl ick ( )

Data1.RecordSet.AddNew

End Sub

This adds a new blank record, you can enter the data you want in the record’s fields, and to update the database, you cl ick the Update button

Updating a Database with ChangesAfter changing the fields in a record, you can update a database with the UpdateRecord method of the data, ADO, or remote data control . For example, when the user cl icks the Update button, we can update the databse with new record l ike this

Private Sub cmdUpdate_Cl ick( )

Data1.UpdateRecord

End Sub

Deleting Records in DatabasesYou can delete a record in a database with the Delete method of the Recordset property of a data or ADO data control , or of the Resultset property of a remote data control . In this example, when the user c l icks the Delete button, we can delete a record l ike this

Private Sub cmdDelete_Cl ick( )

Data1.Recordset.Delete

End Sub

Refreshing a Data ControlWhen working with mult iple databases, you can refresh the data in the current database control with the Refresh method of the data, ADO data control , or the remote data control . Here in this example, when the user cl icks the Refresh button, we can refresh the control l ike this

Private Sub cmdRefresh_Cl ick( )

Data1.Refresh

End Sub

Moving through the Records You can move through the records of a database with MoveNext, MovePrevious, MoveFirst, and MoveLast methods of the Recordset property of Data or ADO data control or of the ResultSet property of Remote data control . Here in this example we’ l l use these four methods to move through records

Private Sub cmdMoveNext_Cl ick( )

Data1.Recordset.MoveNextEnd Sub

Page 114: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 114

Private Sub cmdMovePrevious_Cl ick( )

Data1.Recordset.MovePrevious

End Sub

Private Sub cmdMoveLast_Cl ick( )

Data1.Recordset.MoveLast

End Sub

Private Sub cmdMoveFirst_Cl ick( )

Data1.Recordset.MoveFirst

End Sub

Page 115: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 115

Chapter 23

The Data-Bound ControlsYou can bind certain controls to the data control , the remote data control , and ADO data control , and those controls are cal led bound controls. To bind a control to a database control , you use propert ies l ike DataSource to specify the database control , and then use properties l ike DataField or BoundColumn to specify what field to display in the bound control . Here are the controls that can function as bound controls

Picture Boxes Labels Text Boxes Checkboxes Image Controls OLE controls List Boxes Masked Edit controls Rich Text boxes Combo boxes

In addit ion, there are specia l controls that are designed to be used as bound controls

DBList DBCOmbo FlexGrid MSFlexGrid

Final ly, a no. of bound controls are special ly bui lt to be used with the ADO control only

DataList DataCombo DataGrid

The Data-bound controls in detailAfter instal l ing a data, or ADO data control , you can connect that control to other controls through a process cal led data binding. You bind controls to a data control using the data properties of the bound controls. The standard bound controls and their data properties appear in fo l lowing table.

Control Properties to Set

Checkbox DataField=Desired Boolean field; Data Source = Data control ’s nameCombo box DataField=Desired field;DataSource=Data control ’s nameDBCombo box BoundColumn=Desiredfield; DataField=Desired field;DataSource=Data control ’s name;ListField=Desired field to display in the combo l ist; RowSource=Data control ’s nameDBList box DataField=Desired field; DataSource=Data control ’s name;

RowSource=Data control ’s nameFlexGrid DataSource=DataControl ’s nameImageControl DataField=Desired field; DataSource=Data control ’s nameLabel DataField=Desired field; DataSource=Data Control ’s nameList box Data field=Desired field; DataSource=Data control ’s nameMaskedEdit DataField=Desired field; DataSource=Data control ’s nameMSFlexGrid DataSource=Data control ’s namePicture box DataField=Desired field; DataSource=Data control ’s nameText box DataField=Desired field; DataSource=Data control ’s nameRich Text box DataField=Desired field; DataSource=Data control ’s name

VISUAL BASIC also supports some addit ional data-bound controls to work with ADO data control specifical ly.

The ADO Data-Bound controlsThere are three data-bound controls that are special ly optimized for use with the ADO data control: DataGrid controls, DataCombo controls, and DataList controls. These controls are specifical ly designed to work with ADO Data controls and won’t work with standard controls l ike the data control

To add these controls to a program, fol low these steps

Select Project > Component Click the Controls tab Select both the Microsoft DataGrid Control entry and Microsoft DataList

Controls entry in the List

Click OK to c lose the Components Dialog

Page 116: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 116

This adds the DataGrid, DataCombo, and DataList control tools to the toolbox; draw

these controls as you want on your form

Here are the principle data properties you use with these three controls

DataGrid-DataSource=ADO data control ’s name. You can also set the Al lowAddNew, Al lowDelete, Al lowUpdate propert ies to True or False to enable or Disable those operat ions

DataCombo-DataSource=ADO Data control ’s name; DataField=Name of the field to d isplay in the combo’s text box, L istFie ld=Name of field to d isplay in the l ist , RowSource=ADO data control ’s name, BoundColumn=Name of the source field with which you can provide data to another control

DataList-DataSource=ADO data control ’s name; DataField=Name of the field to display in the current select ion, ListField=Name of field to display in the List, RowSource=ADO data control ’s name, BoundColumn=Name of the source field with which you can provide data to another control

Page 117: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 117

Chapter 24

Working with Database Objects in CodeWorking with data object l ibraries provides more flexibi l i ty, more power and a great deal more complexity for your data base programs

Data Access Objects (DAO)About DAO :-

DAO is the default object model of the data control that you commonly used. The DAO model is optimized for accessing access style, ISAM database over local area network. VISUAL BASIC 6 contains fol lowing DAO l ibraries,

1) DAO 3.51 object l ibraries2) DAO 2.5 / 3.51 compatib i l i ty l ibrary

Record Set : - The primary data object used in DAO is dataset object. This is the object that holds the col lect ion of datarecords used in your VISUAL BASIC program. There are different types of datasets objects,

Working with DAO, you can use the database and Recordset Data Access objects in your procedures. The database and Recordset objects each have propert ies and methods of their own, and you can write procedures that use these properties and methods to manipulate your data.

To open a database in DAO, you just open a Database object or create a new one. This object can represent a Microsoft Jet Database (.mdb) file, an ISAM database (for example, Paradox), or an ODBC database connected through the Microsoft Jet Database Engine. When the database object is avai lable, you create a Recordset object and use that object’s methods, l ike MoveFirst and MoveNext, to work with the database.

DAO also supports a cl ient/server connect ion mode cal led ODBCDirect . ODBCDirect establ ishes a connection directly to an ODBC data source, without loading the Microsoft Jet Database Engine into memory, and is a good solut ion when you need ODBC features in your program.In the ODBCDirect object model, the Connection object contains information about a connection to an ODBC data source, such as the server name, the data source name, and so on. It is similar to a Database object; in fact, a Connection object and a Database object represent different references to the same object.

A Full-Scale DAO ExampleTo i l lustrate DAO data handl ing in code, lets create an example project. This program has a Fi le menu with fol lowing items.

New Database-Creates a new database Open Database-Opens a database Close Database-Closes the current database New Table-Creates a New Table Search-Searches the database Sort-Sorts the database Exit-Exits the Appl ication

Using the DAO code Example to create and Edit a DatabaseTo create a database file, select New Database menu item. Next, add a table to that database with the New Table menu item, then add records to that table. When you’re ready to store the database on disk, use the c lose the Close Database item.

In addit ion, the program has buttons that let users add, edit, update, and delete records, as wel l as lett ing them move through a database. Each t ime you want to add record, cl ick the Add New Record button, type the data for the records fields, and cl ick the Update Database button to update the database.To edit a record, open the record, cl ick the Edit button, edit the data in the record’s fields, and cl ick the Update Database button to update the database. For s implic ity, this program only creates tables with two fields, although you can place as many records as you l ike in each table.

DAO-Creating a DatabaseTo create a DAO database in code, Select Project > References menu item, select the Microsoft DAO object l ibrary, and cl ick OK to c lose the references dialog. Now we can make use of the data objects in that l ibrary to create a new database using CreateDatabase. CreateDatabase is a method of the DAO Workspace object. Here’s how you use CreateDatabase.

Page 118: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 118

Set database=workspace.CreateDatabase( name, locale [,options])

Here are the arguments

Name-A str ing upto 255 characters long that is the name of the database file you’re creating. It can be the ful l path and file name, such as “C:\abc\main.mdb”. i f you don’t supply a filename extension, .mdb is added.

Locale-A str ing that specifies a col lat ing order for creat ing the database, l ike dbLangGeneral , dbLangGreek, and so on.

Here are the possible sett ings for the Options argument

dbEncrypt-Creates an encrypted database dbVersion10-Creates a database that uses the Jet engine version 1 file format dbVersion11-Creates a database that uses the Jet Database engine version

1.1 file format

dbVersion20-Creates a database that uses the Jet database engine version 2 file format.

dbVersion30-The default, Creates a database that uses the Jet database engine

version 3 file format.(compatible with version 3.5)

Lets see an example. When the user selects the New database item in our example DAO program, daocode, we wi l l create a new database. First, we declare that database as a form-wide variable:

Dim db As Database

Next, we add a Common Dialog Control , CommonDialog1, to the program and show it to get the name of the database file the user wants to create. F inal ly, we create the new database, passing the CreateDatabase method the name of the database file and indicating that we want to use the default col lat ing order by passing the constant dbLangGeneral

Private Sub NewDatabase_Cl ick ( )

CommonDialog1.ShowSaveIf CommonDialog1.Fi leName <> “”

Set db=DBEngine.Workspaces(0).CreateDatabase_(CommonDialog1.Fi leName dbLangGeneral)

End I f

End Sub

DAO-Creating a Table with a TableDef Object.You create a table in DAO database with TableDef object. Then you can append fields to the table, and then you can append the new table definit ion to a database’s TableDefs col lection.

Let’s see an example. After the users create a new database with our DAO code example, the daocode project, they can create a new table using the New Table item in the Fi le menu. That i tem opens the New Table dialog box.

Users can enter the name of the new table to create in the text boxes in the New Table dialog box, and we can use that information to create a new TableDef object , which we declare as a form-wide variable.

Dim td As TableDef

We create a new TableDef for the Database object we creates in the previous topic, using the name for the table the user has placed in Text1 in the New Table d ialog box.

Sub CreateTable( )

Set td=db.CreateTableDef(Tableform.Text1.Text)…..

End Sub

This code creates a new, empty TableDef object named td. An empty table isn’t much use, though-we’ l l see about adding fields to this object in the next topic.

DAO-Adding Fields to a TableDef Object

Page 119: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 119

How document you add fields to a DAO TableDef object? You can use that object ’s CreateField method to document that, passing that method the name of the new field and a constant indicating that field’s type.

TableDef.CreateField(FieldName, Fie ldType)

Here are the constants specifying the possib le field types:

dbBigInt dbBinary dbBoolean dbByte dbChar dbCurrency dbDate deDecimal dbDouble dbFloat dbGUID dbInteger dbLong dbLongBinary (OLE object) dbMemo dbNumeric dbSingle dbText dbTime dbTimeStamp dbVarBinary

Let’s see an example to make this clear. We can now add two fields to that object, which we declare in an array named fields of type Field. The users have specified what names they want to give to those two new fields in the New Table Dialog box’s text boxes, so we create the new field this way. Then we can append them to the actual TableDef object.

Sub CreateTable( )

Set td=db.CreateTableDef(Tableform.Text1.Text)Set fields(0)=td.CreateField(TableForm.Text2.Text,dbText)Set fields(1)=td.CreateField(TableForm.Text3.Text,dbText)td.fields.Append fields(0)td.fields.Append fields(1)

End Sub

DAO-Adding an Index to a TableDef ObjectYou use an Index to sort a table, and you create an index with the DAO CreateIndex method. The CreateIndex method creates an Index object, and you can make one of the fields in a table that table’s index with that Index object’s CreateField method.

Let’s see an example to make this clear.

We’ l l create an index for our DAO example, which we declare as a form-wide variable.

Dim dbindex As Index

We name the Index when we create it ; here, we’ l l just use the first field that the user has placed in this table as the table’s index so al l sort operations wi l l sort using that field. In this example, we name our index by adding the word “index” to the name of that field this way. Next, we create a new field, indexfield, in the index, using the name of the first field in the table. F inal ly , we append indexfield to our Index object , dbIndex, and append that object to the TableDef object’s Indexes col lection.

Sub CreateTable( )

Set td=db.CreateTableDef(Tableform.Text1.Text)Set fields(0)=td.CreateField(TableForm.Text2.Text,dbText)Set fields(1)=td.CreateField(TableForm.Text3.Text,dbText)td.fields.Append fields(0)td.fields.Append fields(1)

Set dbIndex=td.CreateIndex(TableForm.Text2.Text & “index”)Set indexfield=dbindex.CreateField(Tableform.Text2.Text)dbindex.fields.Append indexfieldtd. Indexes.Append dbIndex

End Sub

Page 120: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 120

DAO-Creating a Record SetAfter you’ve instal led the new table, you can use the OpenRecordset method to open a record set and start working with data.

Set recordset=Database.OpenRecordset ( Source, type, options, lockedits)

Here are the arguments for OpenRecordset

Source-A str ing specifying the source of the records for the new Recordset object. The source can be a table name, a query name, or an SQL statement that returns records.

Type-Indicates the type of Recordset to open Options-Combinat ion of constants that specify characterist ics of the new

Recordset. Lockedits-Constant that determines the locking for Recordset

Here are the possible sett ings for type

dbOpenTable -Opens a table-type Recordset object dbOpenDynamic -Opens a dynamic-type recordset object, which is l ike an

ODBC dynamic cursor. dbOpenDynaset -Opens a dynaset-type Recordset object, which is l ike an

ODBC keyset cursor. dbOpenSnapshot -Opens a snapshot-type Recordset object, which is l ike an

ODBC stat ic cursor. dbOpenForwardOnly -Opens a forward-only-type Recordset object

Here are the possible sett ings for options dbAppendOnly -Al lows the users to append new records to the Recordset

but prevents them from edit ing or delet ing exist ing records (Microsoft Jet dynaset-type Recordset only)

dbSQLPassThrough -Passes an SQL statement to a Microsoft Jet connected ODBC data source for processing ( Jet Snapshot-type Recordset only)

dbSeeChanges -Generates a runtime error i f one user is changing data that another user is edit ing ( Jet dynaset-type Recordset only)

dbDenyWrite -Prevents other users from modifying or adding records ( Jet Recordset object only)

dbDenyRead-Prevents other users from reading data in a table ( Jet table type recordset only)

dbForwardOnly -Creates a forward-only Recordset ( Jet snapshot-type Recordset only). I t is provided only for backward compatibi l i ty, and you should use the dbOpenForwardOnly constant in the type argument instead of using this opt ion.

dbReadOnly -Prevents users from making changes to the Recordset (Microsoft Jet only). The dbReadOnly constant in the lockedits argument replaces this option, which is provided only for backward compatibi l i ty

dbRunAsync -Runs an asynchronous query (ODBCDirect workspaces only) dbExecDirect -Runs a Query by skipping SQLPrepare and directly cal l ing

SQLExecDirect (ODBCDirect workspaces only) dbInConsistent -Al lows inconsistent updates (Microsoft Jet Dynaset type

and snapshot-type Recordset objects only) dbConsistent -Al lows only consistent updates (Microsoft Jet dynaset type

and snapshot type Recordset object only)

Here are the possible sett ings for the lockedits argument dbReadOnly -Prevents users from making changes to the Recordset (default

for ODBCDirect workspaces) dbPessimistic -Uses pessimist ic locking to determine how changes are made

to the Recordset in a mult i -user environment dbOptimistic -Uses optimist ic locking to determine how changes are made

to the Recordset in a mult i -user environment dbOptimisticValue -Uses optimistic concurrency based on row values

(ODBCDirect workspaces only) dbOptimisticBatch -Enables batch optimistic updat ing (ODBCDirect

workspaces only)Lets see an example to make this clear.

Sub CreateTable( )

Set td=db.CreateTableDef(Tableform.Text1.Text)Set fields(0)=td.CreateField(TableForm.Text2.Text,dbText)Set fields(1)=td.CreateField(TableForm.Text3.Text,dbText)td.fields.Append fields(0)td.fields.Append fields(1)

Set dbIndex=td.CreateIndex(TableForm.Text2.Text & “index”)Set indexfield=dbindex.CreateField(Tableform.Text2.Text)dbindex.fields.Append indexfield

Page 121: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 121

td. Indexes.Append dbIndexdb.TableDefs.Append tdSet dbrecordset=db.OpenRecordset(TableForm.Text1.Text,dbOpenTable)

End SubIn this case, we’re opening the new record set as a standard DAO table by passing the constant dbOpenTable. We also declare dbrecordset as a form wide variable.

Dim dbrecordset As Recordset

DAO-Opening a DatabaseTo open an Exist ing DAO database, you use the DAO OpenDatabase Method, passing it the name of the database to open, and these arguments

Set databaseobject=Workspace.OpenDatabase(dbname, [options [, readonly_ [,connect]]])

Here are the arguments

Dbname-The name of an exist ing database file, or the data source name (DSN) of an ODBC data source.

Options-Sett ing options to True opens the database in Exclusive mode; sett ing it to False (the default) opens the database in shared mode.

Read only-True i f you want to open the database with read-only access, or False (the default) i f you want to open the database with read/write access.

Connect-Opt ional. A Variant (str ing subtype) that specifies various connection information, including passwords.

Let’s see an example, in our project, the user can cl ick the Open Databse menu item to open a database. In the program, we get the name of the database the user wants to open with a Common Dialog Control , and open the database l ike this:

Pr ivate Sub OpenDatabase_Cl ick( )

I f CommonDialog1.Fi lename <> “” ThenSet db = DbEngine.Workspaces(0).OpenDatabase(CommonDialog1.Fi lename)

…End Sub

Next, i f you know the name of the table you want to open in the database, you can open that table by name immediately with the OpenRecordset method. When you open the DAO database, there are a number of system tables already in i t , so to open the first user-defined table, we find the index of that table in the TableDefs col lect ion by first skipping the system tables which have the dbSystemObject flag set in their Attr ibute properties.

Private Sub OpenDatabase_Cl ick( )

I f CommonDialog1.Fi lename <> “” ThenSet db = DbEngine.Workspaces(0).OpenDatabase(CommonDialog1.Fi lename)Tableindex=0

While (db.TableDefs(tableindex).Attr ibutes And dbSystemObject)

Tableindex=Tableindex+1

Wend

End Sub

We’l l open the first table after the system tables. We open a new recordset for that table with OpenRecordset method and fil l the textboxes Text1 and Text2 with fields of first record in that table. The table should have at least one record.

Private Sub OpenDatabase_Cl ick( )

I f CommonDialog1.Fi lename <> “” ThenSet db = DbEngine.Workspaces(0).OpenDatabase(CommonDialog1.Fi lename)Tableindex=0

While (db.TableDefs(tableindex).Attr ibutes And dbSystemObject)

Tableindex=Tableindex+1

Wend

Setdbrecordset=db.OpenRecordset(db.TableDefs(tableindex).Name, dbopenTable)

Set td=db.TableDefs(tableIndex)

Text1.Text=dbrecordset.fields(0)Text2.Text=dbrecordset.fields(1)

End I f

Page 122: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 122

End Sub

DAO-Adding a record to a RecordsetTo add a new record to a DAO recordset, you use the AddNew method. After you’ve updated the fields of the current record, you save the record to the database with Update method.

For example, when the user Cl icks the Add button in our project, the daocode project, we execute the AddNew method on the Programs record set and clear two data field text boxes

Private Sub cmdAdd_Cl ick ( )

Dbrecordset.AddNewText1.Text=””Text2.Text=””

End Sub

Now users can enter data for the new record, and cl ick Update button to save the changes.

DAO-Editing Records in a RecordsetBesides adding new records, users might want to edit the exist ing records, to do thatYou use the Edit method l ike this in our DAO example.

Private Sub cmdEdit_Cl ick ( )

Dbrecordset.Edit

End Sub

After users edit the data in the record’s fields, they must update the database with the new data, and they document that in the daocode project by c l icking Update button.

DAO-Updating a Record in a Record SetWhen the user changes the data in a record or adds a new record, we must update the database to record that change, and you use the record set Update method to document that:

Recordset.Update ([type [, force]])

Here are the arguments in this function:

Type-Constant indicating the type of update, as specified in Sett ings (ODBCDirect workspaces only).

Force-Boolean value indicating whether or not to force the changes into the database, regardless of whether the data has been changed by another user (ODBCDirect workspaces only)

Lets see an example, when the user cl icks the Update button in our project , we wi l l update the database with the new data for the current record. We get the new data for the current record from text boxes Text1 and Text2, where the user has entered data, and load the data into the recordset’s fields using the fields col lection. After loading the data, we save that record using the Update method.

Private Sub cmdUpdate_Cl ick ( )

Dbrecordset.fields(0)=Text1.TextDbrecordset.fields(1)=Text2.TextDbrecordset.Update

End Sub

DAO-Moving through the Records in RecordsetTo move through the records, you use the Move commands MoveFirst , MoveNext, MoveLast, MovePrevious commands. After moving we display the current records data in Text boxes in our example.

To Move to the First Record, execute MoveFirst Method.

Private Sub cmdMoveFirst_Cl ick( )

Dbrecordset.MoveFirstText1.Text=dbRecordset.Fie lds(0)Text2.Text=dbrecordset.Fields(1)

End Sub

Page 123: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 123

To Move to the Next Record, execute MoveNext Method.

Private Sub cmdMoveNext_Cl ick( )

Dbrecordset.MoveNextText1.Text=dbRecordset.Fie lds(0)Text2.Text=dbrecordset.Fields(1)

End Sub

To Move to the Last Record, execute MoveLast Method.

Private Sub cmdMoveLast_Cl ick( )Dbrecordset.MoveLastText1.Text=dbRecordset.Fie lds(0)Text2.Text=dbrecordset.Fields(1)

End Sub

To Move to the Previous Record, execute MovePrevious Method.

Private Sub cmdMovePrevious_Cl ick( )Dbrecordset.MovePreviousText1.Text=dbRecordset.Fie lds(0)Text2.Text=dbrecordset.Fields(1)

End Sub

DAO-Deleting a Record in a RecordsetTo delete a record in a DAO recordset, you use the Delete method, and then you update the recordset. For example when the user c l icks the Delete button in our DAO code example, we clear the textboxes Text1 and Text2, that display the current record and delete that record.

Private Sub cmdDelete_Cl ick ( )

Text1.Text=””Text2.Tex=””Dbrecordset.Delete

End Sub

DAO-Sorting a RecordsetTo sort a recordset, you can instal l the index you want to sort with in the record set’s Index property. For example, we can sort the recordset in our DAO code example, with the Index we’ve created this way. After the record set is sorted, we display the first record in the two main text boxes Trext1 and Text2.

Private Sub cmdSort_Cl ick( )

Set dbindex=td. Indexes(0)Dbrecordset.Index=dbindex.NameText1.Text=dbrecordset.fields(0)Text2.Text=dbrecordset.Fields(1)

End Sub

DAO-Searching a RecordsetYou can search a record set with an index; we just set i ts Index property to the Index we want to search and then set i ts Seek property to the str ing we want to search for. Let’s see an example. When the user selects the Search menu item in our Example, we instal l the index based on the first field in the recordset and show the dialog box named Search. After the user dismisses the search dia log, we retr ieve the text to search for from that text g iven in the search item. In the Seek comparison, besides “=”, you can also use “<”, “<=”, “>=”, and “>”. When the search is complete, we display the found record’s data in the Text boxes.

Private Sub cmdSearch_Cl ick( )

Dim Response As Str ing

Set dbindex=td. Indexes(0)Dbrecordset.Index=dbindex.NameResponse=InputBox(“Enter I tem to search”)

Dbrecordset.Seek “=”, Response

Text1.Text=dbrecordset.Fields(0)Text2.Text=dbrecordset.Fields(1)

Page 124: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 124

End SubDAO-Executing SQLYou can execute an SQL statement when you create a DAO recordset using the OpenRecordset method by placing that SQL statement in the source argument.

Set recordsetobject=Databaseobject.OpenRecordset(source,type,options,_ lockedits)

Here are the arguments for OpenRecordset.

Source-A str ing specifying the source of the records for new Recordset. The source can be a table name, a query name, or an SQL statement that returns records. (for table type recordset the source can only be a table name)

Type-Indicates the type of Recordset to open Options-Combinat ion of constants that specify characterist ics of the new

Recordset. Lockedits-Constant that determines the locking for Recordset.

Here are the possible values for type.

dbOpenTable-Opens a table-type Recordset object dbOpendynamic-Opens a dynamic-type Recordset object, which is l ike an

ODBC dynamic cursor dbOpenDynaset-Opens a dynaset type recordset, which is l ike an ODBC

keyset cursor dbOpenSnapshot-Opens a snapshot type recordset object, which is l ike an

ODBC stat ic cursor dbOpenForwardOnly-Opens a forward-only-type recordset object

Here are the possible values for Options argument

dbAppendOnly-Al lows users to append records to the recordset but prevents from edit ing or deleting exist ing records (Microsoft Jet Dynaset type only)

dbSQLPassThrough-Passes an SQL statement to a Microsoft Jet connected ODBC data source for processing (Microsoft Jet snapshot-type recordset only)

dbSeeChanges-Generates a runt ime error i f one user is changing data that another user is edit ing (Microsoft Jet Dynaset type only)

dbDenyWrite-Prevents other users from modifying or adding records (Microsoft Jet recordset objects only)

dbDenyRead-Prevents other users from reading data in a table (Microsoft table type record set only)

dbForwardOnly-Creates a forward-only recordset (Microsoft Jet snapshot type only). I t is provided only for backward compatibi l i ty, and you should use the dbOpenForwardOnly constant in the type argument instead of using this option

dbReadOnly-Prevents users from making changes to the recordset (Microsoft Jet only). The dbReadOnly constant in the lockedits argument replaces this option, which is provides only for backward compatibi l i ty

dbRunAsync-Runs an asynchronous query (ODBCDirect workspaces only) dbExecDirect-Runs a Query by skipping SQLPrepare and directly cal l ing

SQLExecDirect (ODBCDirect workspaces only) dbInconsistent-Al lows inconsistent updates (Microsoft Jet dynaset type and

snapshot type only) dbConsistent-Al lows only consistent updates (Microsoft Jet dynaset type and

snapshot type only)

Here are the possible sett ings for lockedits argument

dbReadOnly-Prevents users from making changes to the Recordset (default for ODBCDirect workspaces)

dbPessimistic-Uses pessimistic locking to determine how changes are made to the recordset in a mult i -user environment

dbOptimistic-Uses optimistic locking to determine how changes are made to the Recordset in a mult i -user environment

dbOptimisticValue-Uses optimistic concurrency based on row values (ODBCDirect workspaces only)

dbOptimisticBatch-Enables batch optimistic updat ing (ODBCDirect workspaces only)

Any one of these recordset object can be used to gain access to an exist ing table in a database. Each has unique propert ies and behaves differently at t imes.

The dynaset type recordset data object:-VISUAL BASIC dynaset type recordset data object is most frequent ly used in VISUAL

BASIC database program. I t is used to dynamical ly access to part of al l of an exist ing datatable in a database. When you set the database name and recordset property of a

Page 125: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 125

VISUAL BASIC data control , you are actual ly creating dynaset type recordset. Also you can create dynaset method of database object .

Dynaset requires less memory than other data objects and provide the most update option including the capabi l i ty of creating addit ional data objects from exist ing dynaset. Dynaset are the default data object from visual basic data control and they are the only updatable data object you can use for databases connected through Microsoft ODBC(Open Database Connectivity)

Even though dynasets are virtual tables in memory created from physical table, they are not static copy of the datatables. After you created a dynaset, i f anyone alters the data table by modify ing, adding or deleting records you see the change as in your dynaset as soon as your refresh the dynaset. Refreshing the dynaset can be done using refresh method. Dynaset also have some l imitat ions and drawbacks.

E.g. :- i f another user deletes a record that you currently have in your dynaset and you attempt to move that record, VISUAL BASIC wi l l report an error. A dynaset can be created using more than one table. Dynaset type record set can use bookmark, filter, sort, properties to re order data for display you cannot use the seek method on a dynaset type recordset, you can use the find first , find next, find last, find previous methods.

Using the find methods in dynaset object: -Dynaset do not have indexes apply to them. I .e. , you cannot perform a seek action to locate a specific record. However Dynaset wi l l al low sequential searches for an individual record to handle the Dynaset support the four find methods.

1) FindFirst : - starts the search from the first record in the dataset, begins searching for what and returns the first records that matches the search cr iter ia.

2) FindLast : - starts the search from the last record in the data set, begins searching backward and returns the first record that matches the cr iter ia.

3) FindNext : - starts the search From the current record in the dataset, begins searching for what and returns the first record that matches the cr iter ia.

4) FindPrevious : - starts the searching from the current record in the dataset, begins searching backwards and returns the first record that matches the cr iter ia.

Syntax:- Recordset.findfirst”<fieldname><operator><value>”E.g.: rs.findfirst”item = ’tv’ ”

Table type record set data object:-In VISUAL BASIC table type recordset data object g ives you access to the physical

data table, sometimes referred as base table, you can use the table object to directly open the table. The chief advantage of using table object is that you can specify search indexes and use VISUAL BASIC ‘seek’ method. Like dynasets, Tables take a l imited amount of local workstation memory. The table type recordset also g ives you instant information on the state of the data table. This is important in a mult i user environment.

I .e. , i f a user adds or deletes a record from the table, al l other uses for have the database open as VISUAL BASIC table object also see the changes.

VISUAL BASIC table objects have fol lowing drawbacks. You cannot use a select statement (query) to init ial ize a table object. You cannot combine data tables to create unique views when you create table objects. You cannot use bookmarks, create filters or sort the table. Also you cannot use the table data object to access ODBC only. Dynaset and snapshot can be used with ODBC datasources.

The seal strength of a table object is that you can specify index objects to use when searching for specific records in the table. Table objects a lso use l imited workstation memory and offers instant update whenever the data in the table changes.

Like dynasets table objects use l imited workstation memory because VISUAL BASIC catches pointers to the actual records at workstation instead of loading al l the records into workstation memory. This gives your programs the dataset access speed al l of the data object, When you are searching for the single record. Unl ike Dynaset or Snapshot, Table objects are not subset of the datatable. They contain al l the records in the data table at al l t imes.i .e., when a new record is added or a user deletes a record, the table object is updated automatical ly to select the changes.

Table type record sets, Objects, Indexes, Seeks:-

You can use indexes to order the datatable. For displays and reports and to speed searches using seek method.

Seek method:-

E.g. :-

Dim db as databaseDim ss as recordsetSet db=Opendatabase(“c:\abc\stock.mdb”)Set ss=db.OpenRecordset(“sales”,dbopentable)Rs.index=ab {create index ab on sales ( i tem)}Rs.seek”=”,&’tv’

Page 126: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 126

Limitations of table type record set:-

Table type record set has certain drawbacks. They are ,

1) You cannot sort a table 2) You can’t use table type when accessing ODBC datasources3) You can’t use VISUAL BASIC data control to access table type record set.

Unl ike Dynasets and Snapshots, VISUAL BASIC table objects cannot be sorted, filtered or have book mark set . Instead of sort ing, you can use index objects with a table type record set to establ ish the order of data in the table. I f you need to filter the table, you must create a dynaset or snapshot type record set.

You can’t define a table type object to accept the data using ODBC data sources. You must use a dynaset or snapshot object for ODBC data request.

The VISUAL BASIC table type recordset object is the best choice when you need fast searching of large datatables.

However you need to process sets of data instead of s ingle records, the table type object does not work as easi ly as quickly as Dynaset or snapshot.

Snapshot Type Record Set VISUAL BASIC Snapshot type recordset object are almost identical to dynaset type

recordsets in behavior and properties. However these are two major differences snapshot and dynaset.

a) Snapshots are stored entirely in workstation memory.b) Snap-shots are read-only object.

You need to consider several things when using Snapshot data object.E.g. : - Unl ike dynaset object, Snapshots are stored entirely at workstat ion memory. i .e. I f you create a Snapshot object which contains 500 records, al l 500 records are sent from the data table to your workstation memory.Because al l the requested records are loaded to local machine, init ial records of data can take t ime with Snapshot than with Dynaset. However when the data records are retr ieved and stored local ly, subsequent access to record with in the Snapshot object is faster than with Dynaset object,

Snapshot are static views of table. I f you have a set of data records in a Snapshot object, and then some one deletes records from underlying data table, the snap-shot does not reflect the changes.

The only way you can learn about the changes in underlying data table is to create new snapshot by making a new request

A Full-Scale RDO ExampleTo i l lustrate RDO data handl ing in code, here we bui ld ful ly functional RDO project-the rdocode project. This program is designed to open the ODBC data source. Using the buttons in the project you can move through the database, and we’ l l see how to write code for the rdoproject .

RDO-Opening a ConnectionTi open an RDO connection to a database, you can use the RDO OpenConnection method. OpenConnection is a method of the rdoEnvironment object, and you’l l find a col lect ion of those objects in the rdoEngine object’s rdoEnvironments col lection. To add the RDO objects to a program, select the Project > References menu item in VISUAL BASIC, select the Microsoft Remote Data Object entry in the References dia log box, and cl ick OK. Now we’re free to use rdoEnvironment methods l ike OpenConnection.

Workspace.OpenConnection(datasource, [prompt, [read-only, [connect,_ [options]]]])

Here are the arguments to OpenConnection

datasource-The name of the Datasource prompt-ODBC prompting characterist ic rdDriverPrompt asks the user for a

driver/database, rdDriverNoPrompt uses specified driver/database, rdDriverComplete specifies the connection str ing itself , and rdDriverCompleteRequired is the same as rdDriverComplete, with the addit ional requirement that the driver should disable the controls for information not needed for the connection.

read-only-True i f you want to open the data source as read-only connect-The connect str ing options-Set to rdAsyncEnable i f you want to execute commands

asynchronously

Page 127: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 127

Let’s see an example, here we create an rdoEnvironment object named re this way when the form loads:

Dim re As Object

Private Sub Form_Load( )

Set re=rdoEngine.rdoEnvironements(0)

End Sub

Now we open a connection named db to the ODBC source this way

Dim re As ObjectDim db As Connection

Private Sub Form_Load()

Set re=rdoEngine.rdoEnvironments(0)Set db=re.OpenConnection(“db”)

End Sub

RDO-Creating a ResultSetAfter opening an ODBC data source and creat ing an rdoConnection object, we can create an RDO result set to start working with the records in that data source. To create a result set, we can use the rdoConnection method OpenResultset.

Set resultset=rdoConnection.OpenResultset(name, [type, [locktype, [options]]])

Here are the arguments for OpenResultset

name-Source for the result set; can be an rdoTable object, an rdoQuery object, or an SQL statement

type-Specifies the result set type locktype-Can be one of these values: rdConcurReadOnly (read-only),

rdConcurLock (pessimistic concurrency), rdConcurRowVer(optimist ic row-based concurrency), rdConcurValues(opt imist ic value-based concurrency), or rdConcurBatch (optimistic concurrency using batch updates)

options-Set to rdAsyncEnable i f you want to execute commands asynchronously

Here are the possible values for the type argument

dbOpenKeyset-Opens a dynaset-type rdoResultset object, which is l ike an ODBC keyset cursor

dbOpenDynamic-Opens a dynamic-type rdoResultset object, which lets the appl ication see changes made by other users.

dbOpenStatic-Opens a static-type rdoResultset object dbOpenForwardOnly-Opens a forward-only-type rdoResultset object , where

you can only use MoveNext to move

Let’s see an example, Here, we’ l l create an SQL-based result set in our RDO code example, the rdocode project, when the form loads, using the rdoConnect ion object we’ve created-db. In this case, we’ l l set up an SQL statement, SQLSel, to place al l the fields from the data source’s table named students in the result set:

Dim re As ObjectDim db As rdoConnect ionDim SQLSel As Str ing

Private Sub Form_Load()SQLsel=“Select * From Stock”Set re=rdoEngine.rdoEnvironments(0)Set db=re.OpenConnection(“db”)

End Sub

Now, we use OpenResultset to create an rdoResultset object, resultset:

Dim re As ObjectDim db as rdoConnectionDim resultset As rdoResultsetDim SQLSel As Str ing

Private Sub Form_Load()SQLsel-“Select * From Stock”Set re=rdoEngine.rdoEnvironments(0)Set db=re.OpenConnection(“db”)

Set resultset=db.OpenResultset(SQLSel,rdOpenKeyset)End Sub

Page 128: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 128

Now that we’ve opened a result set, we can use rdoResultset methods l ike MoveFirst to move to the first record and display the data in that record’s Name and Grade fields with the rdocode project’s text boxes, Text1 and Text2

Dim re As ObjectDim db as rdoConnectionDim resultset As rdoResultsetDim SQLSel As Str ing

Private Sub Form_Load()

SQLsel-“Select * From Stock”Set re=rdoEngine.rdoEnvironments(0)Set db=re.OpenConnection(“db”)

Set resultset=db.OpenResultset(SQLSel,rdOpenKeyset)Resultset.MoveFirstText1.Text=resultset(“Name”)Text2.Text=resultset(“Qty”)

End Sub

RDO-Moving through the Records in a Result setTo move through the records in a resultset , you can use the rdoResultset’s Move methods l ike MoveFirst, MoveNext, MoveLast and MovePrevious. After moving to the record we display the current record’s data in text boxes.

To move to the First record, you use MoveFirst method

Private Sub cmdMoveFirst_Cl ick()

Resultset.MoveFirstText1.Text=resultset(“Name”)Text2.Text=resultset(“qty”)

End Sub

To move to the Last record, you use MoveLast method

Private Sub cmdMoveLast_Cl ick()

Resultset.MoveLastText1.Text=resultset(“Name”)Text2.Text=resultset(“qty”)

End Sub

To move to the Next record, you use MoveNext method

Private Sub cmdMoveNext_Cl ick()

Resultset.MoveNextText1.Text=resultset(“Name”)Text2.Text=resultset(“qty”)

End Sub

To move to the Previous record, you use MovePrevious method

Private Sub cmdMovePrevious_Cl ick()

Resultset.MovePreviousText1.Text=resultset(“Name”)Text2.Text=resultset(“qty”)

End Sub

RDO-Executing SQLYou can execute SQL statements with RDO objects when you open a result set, you can also execute an SQL statement with the rdoConnection object’s Execute statements l ike this:

SQLSel=”Select * from stock”RdoConnect ion.Execute SQLSel

A Full-Scale ADO Example

Page 129: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 129

To i l lustrate ADO data handl ing in code, we’ l l bui ld an ADO project, the adocode project . This appl icat ion lets you open the main.mdb file using ADO objects to edit records, add records, and even delete records. You can also move through the database using the buttons.

To edit a record, just type the new values into the text boxes and cl ick the Update button. To add a record, use the Add button, type the new values into the text boxes and cl ick Update button.

ADO-Opening a ConnectionThe first step in edit ing an ADO database is to open that database, which is cal led data source in ADO terminology, by sett ing up a Connection object. To use that and other ADO objects in code, you use the Project > References item, select the Microsoft ActiveX Data Objects L ibrary item, and cl ick OK, adding the ADO Object Library to your project .

Now, we are free to create a new ADO Connection object with the Connection object’s Open method.

Connection.Open ConnectionString [,UserID [, Password [, OpenOptions]]]

Here are the arguments

ConnectionStr ing-Str ing containing information UserID-Str ing containing a username to use when establ ishing the

connection OpenOptions- If set to adConnectAsync, the connection wi l l be opened

asynchronously

Let’s see an example, when we start out ADO code example, the adocode project, we’ l l establ ish a connect ion, db, to the database main.mdb.

Private Sub Form_Load( )

Dim db As ConnectionSet db=New Connect ion

Db.Open “PROVIDER=Microsoft. Jet.OLEDB.3.51;Data Source=C:\XYZ\MAIN.MDB;”

End Sub

ADO-Creating a Recordset from a ConnectionNow that you’ve created an ADO connection, you can open a record set from that connection using the Recordset object’s Open method:

Recordset.Open [Source, [ActiveConnection, [Type, [LockType, [Options]]]]

Here are the arguments for this method

Source-A val id Command object variable name, an SQL statement, a tablename, a stored procedure cal l , or the file name of a Recordset.

ActiveConnect ion- A Val id Connect ion object variable name or a str ing containing Connect ionStr ing parameters

Type-Sets the Recordset tyoe Locktype-A Value that determines what type of locking (concurrency) the

provider should use when opening the Recordset Options-A Long value that indicates how the provider should evaluate the

Source argument i f i t represents something other than a Command object, or that the Recordset should be restored from a file where it was previously saved

Here are the possible values for the Type argument

dbOpenKeyset-Opens a dynaset-type Recordset object, which is l ike an ODBC keyset cursor

dbOpenDynamic-Opens a dynamic-type recordset object, which lets the appl ication see changes made by other users

dbOpenStatic-Opens a static-type Recordset object. dbOpenForwardOnly-Opens a Forward-only-type Recordset object, where you

can only use MoveNext to move

Here are the possible values for the LockType argument

adLockReadOnly-The default; read-only adLockPessimistic-Pessimistic locking, record by record adLockOptimistic-Optimistic Locking, record by record adLockBatchOptimist ic-Optimistic batch updates

Page 130: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 130

Here are the possible values for the options argument

adCmdText-Provider should evaluate Source as a definit ion of a Command adCmdTable-ADO should generate an SQL query to return al l rows from the

table named in source adcmdTableDirect-Provider should return al l rows from the table named in

the source adCmdStoredProc-Provider should evaluate source as stored procedure adCmdUnknown-Type of command in the source argument is not known adCommandFi le-Recordset should be restored from the file named in source adExecuteAsync-source should be executed asynchronously adFetchAsync-After the init ial quantity specified in the CacheSize property is

fetched, any remaining rows should be fetched asynchronously

Let’s see an example, in our ADO example, we create a recordset, adoRecordset, by first declaring it a form-wide variable

Dim adoRecordset As Recordset

Next, we select al l the records in the stock table this way when the form loads, using the Open method.

Private Sub Form_Load( )

Dim db As ConnectionDim adoRecordset As RecordsetSet db=New Connect ion

Db.Open “PROVIDER=Microsoft. Jet.OLEDB.3.51;Data_ Source=C:\XYZ\MAIN.MDB;”

Set adoRecordset=New RecordsetadoRecordset.Open “Select Name,Qty from stock”, db, adOpenStatic,_

adLockOptimisticEnd Sub

ADO-Binding Controls to RecordsetsTo bind a control to an ADO recordset object, you just set that control ’s DataSource property to that object, and then set whatever other data propert ies that control needs to have set.

Let ’s see an example, in our ADO example project, we create a recordset, adoRecordset, and open the main.mdb database. We can bind the fields in that database to the text boxes Text1 and Text2.

Private Sub Form-Load()

Dim db As ConnectionSet db=New Connect ion

db.Open “PROVIDER=Microsoft. Jet.OLEDB.3.51;Data Source=_C:\XYZ\MAIN.MDB;”

Set adoRecordset=New RecordsetAdoRecordset.Open “Select Name, Qty from Stock”, _

db, adOpenstat ic, adLockOptimistic

Set Text1.DataSource=adoRecordsetText1.DataField=”Name”Set Text2.DataSource=adoRecordsetText2.DataField=”Qty”

End Sub

ADO-Adding a Record to a RecordsetTo add a new record to an ADO record set, you use the AddNew method. After you’ve updated the fields of the current record, you save that record to the database with the Update method. Here’s how you use AddNew.

Recordset.AddNew [Fields [ , Values]]

Here are the arguments for this method

Fields-A single name or an array of names or ordinal posit ions of the fields in the new record

Values-A single value or an array of values for the fields in the new record. I f fields is an array, Values must also be an array with the same number of members. The order of field names must match the order of field values in each array

Page 131: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 131

Let’s see an example, here we’l l add a new record to the record set adoRecordset in our ADO code Example, the adocode example, when the user c l icks the appropriate button.

Private Sub cmdAdd_Cl ick()

On Error GoTo ErrLabelAdoRecordset.AddNew

Text1.Text=””Text2.Text=””

Exit Sub

ErrLabel:MsgBox Err.Description

End Sub

ADO-Refreshing the RecordsetSometimes you want to refresh the data in a recordset-you might be deal ing with mult iply-connected databases, for instance, where other users are making changes as wel l -and you can use the ADO Refresh method for that. Let’s see an example. Here, we’ l l refresh the recordset in our ADO code example, the adocode example, when the user Cl icks the appropriate button.

Private Sub cmdRefresh_Cl ick( )

AdoRecordset.Requery

End Sub

ADO-Updating a Record in a RecordsetAfter changing the data in a record’s fields or adding a new record, you update the data source to record the change, using the Update method.

Recordset.Update Fields, Values

Here are the arguments for this method

Fields-A single name or an array of names or ordinal posit ions of the fields in the new record.

Values-A Single value or an array of values for the fields in the new record. I f fields is an array, Values must also be an array with the same number of members. The order of field names must match the order of field values in each array.

Let’s see an example, When users want to update records in our ADO code example, they cl ick the appropriate button, and we’ l l update the data source this way.

Private Sub cmdUpdate_Cl ick ( )

adoRecordset.Update

End Sub

ADO-Moving through the Records in RecordsetTo move through the records in a record set of ADO type, you use the four Move methods MoveFirst, MoveLast, MoveNext and MovePrevious. After moving to the record we display the current record in Text boxes

To Move to the First record, use MoveFirst method

Private Sub cmdMoveFirst_Cl ick ( )

adoRecordset.MoveFirstText1.Text=adoRecordset(“Name”)Text2.Text=adoRecordset(“Qty”)

End Sub

To Move to the Last record, use MoveLast method

Private Sub cmdMoveLast_Cl ick ( )

adoRecordset.MoveLastText1.Text=adoRecordset(“Name”)Text2.Text=adoRecordset(“Qty”)

End Sub

Page 132: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 132

To Move to the Next record, use MoveNext method

Private Sub cmdMoveNext_Cl ick ( )

adoRecordset.MoveNext

If adoRecordset.EOF=True then adoRecordset.MoveLast

Text1.Text=adoRecordset(“Name”)Text2.Text=adoRecordset(“Qty”)

End Sub

To Move to the Previous record, use MovePrevious method

Private Sub cmdMovePrevious_Cl ick ( )

adoRecordset.MovePrevious

If adoRecordset.BOF Then adoRecordset.MoveFirst

Text1.Text=adoRecordset(“Name”)Text2.Text=adoRecordset(“Qty”)

End Sub

ADO-Deleting a Record in a RecordsetTo delete a record in an ADO record set, you use the Delete method

Recordset.Delete AffectRecords

Here, AffectRecords is a value that determines how many records the Delete method wi l l affect. I t can be one of the fol lowing constants

adAffectCurrent-The default; deletes only the Current record adAffectGroup-Deletes the record that satisfy the current Fi l ter property

sett ing

Let’s see an example, Here we delete a record in our ADO code example, when the user presses the appropriate button. In addit ion, we move to the next record in this way

Private Sub cmdDelete_Cl ick( )

On Error GoTo ErrLabel

adoRecordset.Delete

adoRecordset.MoveNext

If adoRecordset.EOF Then adoRecordset.MoveLast

Exit Sub

ErrLabel:

MsgBox Err.Description

End Sub

ADO-Executing SQL in a RecordsetYou can execute an SQL statement when you open a record set using the Open method by passing that statement as the Source argument

Recordset.Open [source, [ActiveConnection, [Type, [LockType, [Options]]]]

Here are the arguments for this method

source-A Val id Command object variable name, an SQL statement, a table name, a stores procedure cal l , or the file name of a Recordset.

ActiveConnect ion-A val id Connect ion object variable name or a str ing containing Connect ionStr ing parameters

Type-Sets the Recordset type LockType-A Value that determines what type of locking (concurrency) the

provider should use when opening the Recordset object Options-A Long value that indicates how the provider should evaluate the

Source argument i f i t represents something other than a Command object, or that the Recordset object should be restored from a file where it was previously saved

Page 133: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 133

Here are the Possible values for the Type argument

dbOpenKeyset-Opens a dynaset-type recordset object, which is l ike an ODBC keyset cursor

dbOpenDynamic-Opens a dynamic-type recordset object, which lets the appl ication see changes made by the users

dbOpenStatic-Opens a static-type Recordset object dbOpenForwardOnly-Opens a forward-only-type recordset object, where you

can only use Movenext to move

Here are the possible values for the Locktype argument

adCmdText-Provider should evaluate source as a definit ion of a command adCmdTable-ADO should generate an SQL query to return al l rows from the

table named in source adCmdTableDirect-Provider should return al l rows from the table named in

Source adCmdStoredProc-Provider should evaluate source as a stored procedure adCmdUnknown-Type of command in the source argument is not known adCommandFi le-Record set should be restored from the file named in source adExecuteAsync-source should be executed asynchronously adFetchAsync-After the init ial quantity specified in the CacheSize property is

fetched, any remaining rows should be fetched asynchronously

Here is an example where we open a record set with the SQL statement

adoRecordset.Open “Select * from stock”, db, adOpenStatic, adLockOptimistic

Page 134: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 134

Chapter 25

Creating Reports- Data Report Understanding Report Writing

Report writ ing is the method by which data is pul led from your database and displayed in a printed format, Web page, or text file. A printed report is , in many situat ions, the ult imate product of your database appl ication. With the release of Microsoft Visual Basic 6.0, Microsoft has introduced the Data Report for creat ing Reports. This tool uses the ADO Data environment to extract data from a data source as a basis of the report .

Creating the Report with Data Report Designer

There are three main steps in creating a Report. The first is to define the connect ion to your data by bui lding the Data Environment. The second step in creating the report is to bind the report to the Data Environment and add fields and other objects. The third and final step is to cal l the report from within your Visual Basic program using Show method.

Steps to create a Report using Data Report Designer

Start a New Standard EXE project

Insert a Data Environment into your project using Project > Add Data Environment menu item.

You create the Data Environment to store the definit ion of the dataset to be used in the report . Double-cl ick on the Data Environment designer. Cl ick on the Connection1 and select Properties from the menu that appears. To create the connection, Cl ick on the Next button after selecting Provider name in the properties box. This brings up the Connections tab. Select the second opt ion, Use connectionstr ing and then cl ick bui ld button. Select the Database and Cl ick next button. To define the datasource, c l ick on the select button in the databsse section of the dialog. Select the database filename and cl ick OK. Test your connection using Test Connect ion button.

Now you can define the Command object. The Command stores connection to the table and the fields that are used on the report . Right-c l ick on Commands in the Data Environment designer and select Add Command. Set the command name. Open the connection combo box and select the connection name you have created. Select Table from that combo box. Al l the tables in your database wi l l be displayed in the combo. You have now completed al l the Data Environment work necessary to create a simple l ist report .

Now it ’s t ime to create the report . To do this, add a Data report designer from Project menu. Double c l ick on data report1 in project explorer window, set i ts name. Set the Datasource property to data environment and datamember property to command object name. You can now add fields to your data report . To do this, you display the Data Environment by double-c l icking on it in the Project Explorer window. Simply cl ick and drag fields from the Data Environment to the Data Report.

The Show method is used to display your report from visual basic. For example

Private Sub mnuReport_Cl ick ( )

DataReport1.Show

End Sub

Formatting the Report

The packaging of your reports is often just as important as the information contained within. Users g ive greater credibi l i ty to reports that have a pol ished look.

Defining Row Spacing on your Report

The Data Report uses the amount of space in Detai l section of the report to gauge space between records. To reduce the amount of space, you drag and reduce the size of Detai l section.

Inserting Column Headings on your Report

Open the data report, Choose View > ToolBox to display the Toolbox. Double cl ick on RptLabel control . Drag the control into Page header section of your report and set i ts caption property. Simil iary create column headings for a l l your fields.

Inserting Headers and Footers

All good printer reports have certain characterist ics. That is the name of report, date, page numbers etc. These items are best placed in the Report Header and Report Footer

Page 135: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 135

sections of your report. To add Report header and Footer, r ight-cl ick on the report and select

Show Report Header/Footer.

Inserting Controls in Report

To insert controls in your report choose Insert >Control > Current Date menu option. To put a page number, select Insert Control >Current Page Number.

Creating Reports Using SQL statements

The data reporter enables you to create reports using SQL statements as the basis for the Command object.

Grouping Records in Data Reports

Add a Grouping in the Data Environment to enable you to group the report by t i t les. To do this, double cl ick on the data desinger, r ight-c l ick on the command object and select properties. Check the Group command on Grouping tab. Cl ick the field in the command l ist box and move it to the fields used for grouping l ist box. Select ok.

Adding Aggregate functions in Report

Aggregate functions can be added to a Data Environment and dragged onto a data report to do most basic math functions, including average, count, sum, maximum, minimum and standard deviation.

Exporting Data

The Data report is also a good tool for extracting data to other appl ications or for publ ishing information to a Web page. After the report is generated, you have the choice of saving it to HTML and Text formats. Try this by generating the report once again. When the print preview appears, select Export icon at top of screen and save the report in HTML format.

Page 136: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 136

Chapter 26

Image Lists, List Views, Tree Views and Tab Strips

Image Lists

Image List controls are invis ible controls that serve one purpose: to hold images that are used by other controls. Usual ly, you add images to an image l ist control at design t ime, using the insert picture button in the control ’s property pages. You can also add images to an image l ist at run t ime, using Add method of i ts internal image col lection, List Images.

To use the images in the image l ist, you usual ly associate the image l ist with a Windows Common Control . You can also reach the images in an image l ist with the ListImages col lection’s Picture property. For Eg. , i f you wanted to use an image l ist with a control that’s not a Windows common control , such as a picture box, you can assign the first image in the image control to that picture box this way

Picture1.Picture = ImageList1.ListImages(1) .Picture

To add an image l ist, Select Project > Components > Windows Common ControlsTo add images to the Imagel ist , r ight cl ick on it and choose Properties, which wi l l br ing the Property pages. Cl ick the images tab and cl ick Insert Picture button to add Images. Each successive image gets a new Index Value, start ing at 1 and count ing up. I f you wish, you can also give each image a Key Value by entering text in the box labeled Key when you add an image.

Also you can add images to an Imagel ist at runt ime, using the ListImages col lection’s Add method. For eg,

ImageList1.ListImages.Add , “Tools”, LoadPicture(“C:\abc.bmp”)

Tree Views

Tree views present data in a hierarchical way, such as the view of directories that appears in the tree view at left in Windows Explorer. Trees are composed of cascading branches of nodes, and each node usual ly consists of an image and a label. Images for nodes are suppl ied by an imagel ist control associated with tree view control . A node can be expanded or col lapsed, depending on whether or not the node has chi ld nodes. At the topmost level are root nodes, and each root node can have any number of chi ld nodes. Each node in a tree actual ly a programmable node object, which belongs to the nodes col lection. As with other col lections, each member of the col lection has a unique Index and Key property that al lows you to access the properties of the node.

To add Tree View Control , Select Project > Components > Microsoft Windows Common ControlsWhen you first add the tree view control , there are only sample nodes vis ible in i t , and nothing at runtime. You’re responsible for adding the nodes and sett ing up their relat ionships, text, and images yourself . There are many different styles for tree views- text nodes only, pictures and text nodes, showing or not showing the tree l ines that connect nodes etc. You set the tree view’s style using its Style property. Here are the possible values

tvwTextOnly - 0tvwPictureText - 1tvwPlusMinusText - 2tvwPlusPictureText - 3tvwTreeLinesText - 4tvwTreeLinePictureText 5tvwTreeLinesPlusMinusText 6tvwTreeLinesPlusMinusPictureText 7

You actual ly add Node objects to a tree view by adding them to the Nodes col lection. For Example

Private Sub Form_Load()

Dim Node1 As Node

Set Node1=TreeView1.Nodes.AddNode1.Text=”Node 1”TreeView1.Nodes(1).Key=”Node 1”

End Sub

You can add other nodes by dupl icating the preceding code and naming Node2, Node3 and so on. But, they wi l l appear in the same level.

Page 137: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 137

Adding Subnodes to a TreeView

When you add a new node to a tree v iew’s Nodes col lect ion, using Add method, you can specify how it is related to the nodes already there. The syntax for Add method is

Nodes.Add(relative, [relationship] [,Key] [,text] [, image] [selectedimage])

The relative argument is another node that you’re relat ing the new node to with relat ionship argument. The possible values for relationship are

tvwLast - 1; the node is places after a l l other nodes at the same level of the

node named in relative.tvwNext - 2; the node is placed after the node named in relativetvwPrevious - 3; the node is placed before the node named in relativetvwChild - 4; the node becomes a chi ld node of the node named in relative

Adding Images to TreeView

To add an image to a node in a tree view, you just have to set i ts Image property to an Index or key in the tree view’s associated imagel ist control .

Expanding and Collapsing Nodes

When the user cl icks a plus or minus sign in a tree view to expand or contract a node. How can we make the nodes image match. When the user c loses a node, the tree view control generates a Col lapse event. In that event handler, we can set the node’s image to the closed folder by referr ing to that Image by its key.

Private Sub TreeView1_Colapse (ByVal Node As Comctl ib .Node)Node.Image=”closed” ‘ closed is the key value for the

imageEnd Sub

Simil iar ly, when the user expands a node, the treeview control generated an Expand Event. In that event handler we can write as fol lows

Private Sub TreeVeiw1_Expand( ByVal Node As Comctl ib .Node)Node.Image=”Open” ‘open is the key value for image

End Sub

Sample Code

Add a TreeView Control TreeView1, and ImageList ImageList1. Add two pictures in Imagel ist and change key property for the images as “closed” and “leaf”

Private Sub Form-Load( )Dim Node1, Node2, Node3, Node4 As Node

Set Node1 = TreeView.Nodes.AddTreeView1.Nodes(1).Text=”Node 1”TreeView1.Nodes(1).Key=”Node 1”TreeView1.Nodes(1). Image=”closed”

Set Node2 = TreeView.Nodes.Add (“Node 1”, tvwChild, “Node 2”)TreeView1.Nodes(2).Text=”Node 2”TreeView1.Nodes(2).Key=”Node 2”TreeView1.Nodes(2). Image=”leaf”

Set Node3 = TreeView.Nodes.Add (“Node 1”, tvwChild, “Node 3”)TreeView1.Nodes(3).Text=”Node 3”TreeView1.Nodes(3).Key=”Node 3”TreeView1.Nodes(3). Image=”closed”

Set Node4 = TreeView.Nodes.Add (“Node 3”, tvwChild, “Node 4”)

Page 138: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 138

TreeView1.Nodes(4).Text=”Node 1”TreeView1.Nodes(4).Key=”Node 1”TreeView1.Nodes(4). Image=”leaf”

End Sub

List Views

The ListView control displays, as i ts name implies, l ists of i tems. You can see a l ist view at r ight in the Windows Explorer. Each item in a ListView is displaying a l ist of files. Each item in a l ist view control is i tself a ListI tem object and can have both text and an image associated with it . The ListI tem objects are stored in the l ist view’s L ist Items col lect ion

ListViews candisplay data in four different view modes.

Iconmode - Can be manipulated with the mouse, al lowing the user to drag and drop and

rarrange objectsSmall Iconmode Allows more List Item objects to be viewed. Like the Icon View mode, objects

can be rearranged by the userListmode - Presents a sorted view of the ListI tem objectsReportmode - Presents a sorted view, with sub- items, al lowing extra information to be

Displayed

You usual ly associate two image l ist controls with a l ist view: one to hold the icons for the Icon view mode, and one to hold small icons for other three modes.

To add a ListView control , Select Windows Common Controls i tem from Project > Components

You add items to a l ist view’s ListI tems col lection, using Add method. Each item you add

is a ListI tem object.

Each item in a ListView is a ListI tem object, and each such object has an Icon property. You set this property to an image’s index or Key in an image l ist control .

Add an ImageList, Imagel ist1 and add an image namely new.bmp

To connect the image l ist with ListView, select the property pages of ListView, Cl ick the ImageLists tab and Select ImageList1 in the box labeled Normal.

Add another ImageList control , namely Imagel ist2, add an image namely leaf.bmp, connect with L istView control and c l ick ok

For Eg.

Private Sub Form_Load ( )Dim List Item1 As L istItemSet ListI tem1= ListView1.List Items.Add( )ListI tem1.Text=”Item 1”ListI tem1.Icon=1ListI tem1.Small Icon=1

Dim List Item2 As L istItemSet ListI tem2= ListView1.List Items.Add( )ListI tem2.Text=”Item 2”ListI tem2.Icon=1ListI tem2.Small Icon=1

Dim List Item3 As L istItemSet ListI tem3= ListView1.List Items.Add( )ListI tem3.Text=”Item 3”ListI tem3.Icon=1ListI tem3.Small Icon=1

End Sub

Page 139: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 139

ListViews can display l ists arranges in columns when you set their View property to lvwReport. To add columns to a l ist view, you just need to add column headers, and you do that with the l ist view’s ColumnHeaders col lection.

Private sub Form_Load()

Dim colHeader as ColumnHeaderDim intLoopIndex As Integer

For intLoopindex= 1 to 4Set colHeader=ListView1.ColumnHeaders.Add()ColHeader.Text=”Field” & intLoopIndexColHeader.Width=ListView1.Width/4

NextEnd Sub

Tab StripsYou can group dialog boxes into one using Tabstr ip. As the user selects the tab in the tabstr ip, you can display the contents that were separate dialog boxes in panels that appear when their tab is cl icked. To add a Tabstr ip, select Project > Components > Windows Common Controls.

After you add a tabstr ip control , you can add new tabs, text, and images to those tabs. At design t ime, you use the tab str ips property pages and add new tabs by c l ick ing Insert Tab button. You can set the each tab’s Text, Key properties etc. at runt ime to add tabs use tabstr ip’s Tabs property, using Add method. You can set the Caption of each tab

using Caption property. To set images for tab, add imagel ist control , imagel ist1, add images to i te and connect with tabs in the tabstr ip.

Sample Code

Private Sub Form_Load( )Dim Tab2, Tab3 as Comctl ib.Tab

Set Tab1=TabStrip1.Tabs(1)Tab1.Key=”Key 1”Tab1.Caption=”Tab 1”Tab1. Image=1

Set Tab2=TabStrip1.Tabs.Add()Tab2.Key=”Key 2”Tab2.Caption=”Tab 2”Tab2. Image=2

Set Tab3=TabStrip1.Tabs.Add()Tab3.Key=”Key 3”Tab3.Caption=”Tab 3”Tab3. Image=3

End Sub

Page 140: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 140

Chapter 27

File HandlingFile HandlingThere are three main ways in VB to access files in Visual Basic: as sequential files, as random access files, and as binary files.

Sequential Access Files

Sequential files are l ike tape cassettes-you read data from them in a sequent ial manner. I f you want data at the end of the file, you have to read al l the intervening data first. Sequential files are often organized into text str ings in Visual Basic. Here are the Visual Basic statements and funct ions you use with sequentia l files

Open Line Input # Print # Write # Input $ Input # Close

In addit ion, Visual Basic supports Textstream objects to make working with sequentia l files easier. Here are the major Textstream methods

Read ReadAll ReadLine Write WriteBlankLines WriteLine Close

If you’ve got a text file ful l of variable- length str ings, you usual ly treat that file as sequential . You can also use sequent ial files to store binary-format items l ike numbers.

Random Access Files

I f sequent ial files are l ike cassetes, Random access files are more l ike CDs. Random files are organized into records usual ly of the same length, and you can read a particular record without having to read al l the intervening data-you can move to that record in a file d irect ly, just as you can move to a CD track.

Here are the Visual Basic statements and functions you use with random access files

Type…End Type Open Put # Len Seek LOC Get # Close

If you want to create your own database files, formatted as you want them, you’d organize them into records. In fact, any file that you want to organize into records is best formatted as a random access file.

Binary Files

Binary files are simply unformatted binary data, and Visual Basic does not interpret ( such as looking for text str ings) or organize the contents ( into records) of such files at al l . These files are just bytes to Visual Basic, and the statements and functions you usual ly use with these files include the fol lowing

Open Get Put Seek Close

Binary files include EXE files, graphic files, and so on.

Page 141: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 141

The FileSystem Object

Besides the preceding file types, Visual Basic includes the Fi leSystemObject for easy file manipulation on disk. This object includes a number of methods for copying, moving, and deleting files such as these GetFi le CopyFi le DeleteFi le MoveFi les Fi leExists CreateFolder CreateTextFi le OpenTextFi le

In fact , you use the Fi leSystemObject to create TextStream objects with methods l ike CreateTextFi le and OpenTextFi le.

Creating A File

The standard way is to use the Open statement. Here’s how the Open statement works:

Open pathname For mode [Access access] [Lock] As [#] filenumber [Len=reclength]

Pathname -A filename (may include directory or folder and drive) Mode -A keyword specifying the file mode: Append, Binary, Input, Output, or

Random (i f unspecified, the file is opened for Random access) Access -A Keyword specifying the operations permitted on the open file: Read,

Write, or Read Write. Lock -A keyword specifying the operations restr icted on the open file by other

processes: Shared, Lock Read, Lock Write, and Lock Read Write. Filenumber-A Val id filenumber in the range 1 to 511, inclusive. Use the FreeFi le

function to obtain the next avai lable filenumber. Reclength-A number less than or equal to 32767. For files opened for random

access, this value is the record length. For sequential files, this value is the number of characters buffered.

If the file is already opened by another process and the specified type of access is not al lowed, the Open operation fai ls and an error occurs. Also note that the Len c lause is ignored i f mode is Binary. I f the file specified by pathname doesn’t exist, i t is created when a file is opened for Append, Binary, Output, or Random modes. After you’ve created the file, you refer to i t using the file number. The fol lowing example let users write the text in a text box, Text1 to a file on disk, file.txt, when they press a button.

Private Sub Command1_Cl ick()On Error GoTo Fi leErrorOpen “C:\file.txt” For Output as #1Print #1, Text1.TextClose #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Getting a File’s Length

There are two ways to determine the length of a file, the Fi leLen and LOF functions.

The FileLen function

The Fi leLen function returns the length of a file in bytes on disk. For example

Private Sub Command1_Cl ick()MsgBox “The file.txt file is” & Str(Fi leLen(“C;\Fi le.txt”)) & “bytes long”

End Sub

The LOF function

The LOF function returns the length of a file in bytes opened with the Open statement. You pass the LOF function an open file number. For example

Private Sub Command1_Cl ick()On Error GoTo Fi leErrorOpen “c:\file.txt” For Output As #1Print #1, Text1.TextMsgBox “The file is “ & Str(LOF(1)) & “bytes long”Close #1Exit SubFi leError:

MsgBox “Fi leError”End SubOpening A File

Page 142: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 142

Use the Open statement to open a file. I f the file is a lready opened by another process and the specified type of access is not al lowed, the Open statement fai ls and an error occurs. Also note that the Len clause is ignored i f mode is Binary. I f the file specified by pathname doesn’t exist, i t is created when a file is opened for Append, Binary, Output, or Random modes. I f you open an exist ing file for output, i t is overwritten; i f you open it for Append, new data is added to the end of the file. After you’ve created the file, you refer to i t using the file number.

Open pathname For mode [Access access] [Lock] As [#] filenumber [Len=reclength]

The fol lowing example opens a file named file.txt and write the contents of a textbox, Text1, to that file

Private Sub Command1_Cl ick()On Error GoTo Fi leErrorOpen “C:\file.txt” For Output as #1Print #1, Text1.TextClose #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Writing to a Sequential File

Sequential files are often text str ings in Visual Basic, but they can also be combinations of text and numbers. You usual ly use these standard statements to write to sequentia l files in Visual Basic

Print # number, expressionlist

Write # number, expressionlist

Here number is an open file number and expressionl ist is a l ist of variables to write, separated by commas.

The Print # statement

I f you want to store your data in text format, use Print #. As an example, we’ l l store the text in a textbox to a file names file.txt using Print #.

Private Sub Command1_Cl ick( )On Error GoTo Fi leErrorOpen “C:\file.txt” For output as #1Print #1, Text1.TextClose #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

The Write # Statement

Ypu can also use the Write # statement to write text and other types of data to a file. You use this statement with a filenumber and a comma-del imited l ist of the variables you want to write to that file. For Example, here we open a file, data.dat, and write two numbers that the user has entered in the text boxes Text1 and Text2 to that file.

Private Sub Command1_Cl ick()Open “C:\data.dat” For Output as #1Write #1, Val(Text1.Text), Val (text2.Text)Close #1

End Sub

Writing to a Random Access File

You usual ly write records to random access files using Put statement:

Put [#]filenumber, [recnumber], varname

Here, filenumber is the number of a file to write to, recnumber is the number of the record to write, and varname is the name of the variable that holds the data to sr ite to the file.

To work with records in a random access file, you define a record type first . For Example, here we define a new type named Record in a module, you can only define types in modules.

Page 143: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 143

Type RecordName As Str ing * 50Number As Str ing * 50

End Type

Note that we use fixed- length str ings here to make al l our records the same size.

Now, in a program, we can set up an array of such records in the General part of a form, as wel l as an integer to keep track of the total number of records.

Dim SriteData(1 to 50) As RecordDim TotalRecords As Integer

In this example, we’l l just have one record, which we fil l from the text boxes Text1 and Text2 when the user cl icks a button. Next, we create a file to store our records in. final ly we use the Put statement to sr ite the data to the file.

Private Sub Command1_Cl ick()WriteData(1).Name=Text1.TextWriteData(1).Number=Text2.TextTotalRecords=1

On Error GoTo Fi leErrorOpen “C:\records.dat” For random as #1 Len =Len(WriteData(1))For Loop_index =1 to TotalRecords

Put #1, WriteData(Loop_index)Next

Close #1Exit Sub

Fi leError:MsgBox ”Fi le Error”

End Sub

Writing to a Binary File

You usual ly write records to binary files using Put statement

Put [#]filenumber, [recnumber], varname

Here is an example showing how to use Put to sr ite a floating point number the user has entered in a text box, Text1, to a file-note that we open that file in b inary mode and don’t use a record number with Put here.

Private Sub Command1_Cl ick()Dim VarOutPut As DoubleVarOutPut=Val(Text1.Text)

On Error GoTo Fi leErrorOpen “C:\binary.dat” For Binary As #1Put #1, , varoutputClose #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Reading From Sequential Files

To read from a sequentia l file, you can use these statements.

Input # number, expressionlist

Line Input # number, string

Input$ (numberbytes, [#] number)

Here number is a filenumber, expressionl ist is a l ist of variables the data wi l l be stored in, str ing is a st ing variable to store data in, and numberbytes is the number of bytes you want to read.

The Input # statement

You can use the Input # statement to read text and numbers from a sequential file. For example, i f we write two integers the user has entered in Text1 and Text2 to a file, data.dat, this way using Write # when the user cl icks Command1.

Page 144: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 144

Private Sub Command1_Cl ick()Open “C:\data.dat” For Output As #1Write #1, Val (Text1.Text), Val(Text2.Text)Close #1

End Sub

Then we can read those integers back using Input # this way when the user c l icks Command2.

Private Sub Command2_Cl ick ()Dim int1, int2 as Integer

Open “C:\data.dat” For Input As #1Input #1, int1, int2Text3.Text=Str( int1)Text4.Text=Str( int2)Close #1

End Sub

The Line Input Statement

Using the L ine Input statement, you can read l ines (text str ings that end with a carr iage return or carr iage return/l ine feed pair) from a file. For example, say we had this set of l ines, each separated by a carr iage return/l ine feed pair in a file named file.txt :

Here is someMult i - l ine textThat weWil l read in…

When the user cl icks a button, we can read in the preceding text l ine by l ine with Line Input. Next we use the EOF funct ion, which returns True when we reach the end of the file.Next, we use Line Input statement to read l ine of text from the file and append them to a mult i - l ine text box, Text1, along with a carr iage return l ine feed pair this way.

Private Sub Command1_Cl ick ( )Dim NewLine As Str ing

On Error GoTo Fi leErrorOpen “C:\file.txt” For Input As #1Do unti l l EOF(1)

Line Input #1, NewLineText1.Text=Text1.Text + NewLine +vbCrLf

Loop

Exit Sub

Fi le Error:MsgBox “Fi le Error”

End Sub

The Input$ Statement

The Input$ statement lets you read in a str ing of a specified length. I t might seem odd to have to know the str ing’s lengths before reading them in, but Input$ does have one very useful aspect: i f you use it together with the LOF funct ion, you can read in a whole text file at once.

For Example, here’s how we read in the file from the previous example, file.txt, al l at once, without having to work l ine by l ine.

Private Sub Command1_Cl ick()Dim NewLine As Str ing

On Error GoTo Fi leErrorOpen “C:\file.txt” For Input As #1

Text1.Text = Input$(LOF(1), #1)Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Reading From Random Access Files

You use Get to read records from a random access file.

Get [#]filenumber, [recnumber], varname

Page 145: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 145

Here, filenumber is the number of a file to read from, recnumber is the number of the record to read, and varname is the name of the variable that should receive the read-in data.

Let’s see an example, we set up a new type named Record in a module:

Type RecordName As Str ing * 50Number As Str ing * 50

End Type

Then we set up two formwide arrays of records, WriteData and ReadData, and an Integer named TotalRecords to keep track of how many records are total .

Dim WriteDetai l ( 1 to 50) As RecordDim ReadDetai l (1 to 50 ) As RecordDim TotalRecords As Integer

When the user c l icked a command button, we read the text from two text boxes, Text1 and Text2, placed that text in the first record of the WriteData array, and wrote that record out to a file named records.dat with the Put statement.

Private Sub Command1_Cl ick()WriteData(1).Name=Text1.TextWriteData(1).Number=Text2.TextTotalRecords =1

On Error GoTo Fi leErrorOpen “C:\records.dat” For Random As #1 Len = Len(WriteData(1))For intLoopIndex = 1 to TotalRecordsPut #1, , WriteData(IntLoopindex)Next

Close #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Now, we’l l see how to read that record back in, first, we open the file records.dat for random access, sett ing the records size to the length of each array element. Then we use Get statement to read in the records. Next, we loop over al l the records in the file. Then we close the file and display the Name and Number fields on the first record in two text boxes Text3 and Text4

Private Sub Command2_Cl ick( )On Error GoTo Fi leError

Dim intLoopindex As Integer

Open “C:\records.dat” For Random As #1 Len=Len(ReadData(1))

For IntLoopindex=1 to LOF(1) / Len(ReadData(1))Get #1, , ReadData(IntLoopIndex)

Next

Close #1Text3.Text=ReadData(1).NameText4.Text=ReadData(1).Number

Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Reading From Binary Files

You usual ly use Get to read data from a binary file

Get [#]filenumber, [recnumber], varname

Let’s see an example. In this case, we first write some binary data-such as a floating number-to a file, and then we’ l l read it back in. here, we let the user enter a Double value in a text box, which we read in when the user c l icks a command button, Command1. Then we write that number out to a binary file, binary.dat.

Page 146: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 146

Private Sub Command1_Cl ick ()Dim varoutput As DoubleVaroutput=Val(Text1.Text)

On Error GoTo Fi leErrorOpen “C:\binary.dat” For Binary As #1Put #1, , varoutputClose #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

next we read that number back in as binary data when the user cl icks a new button Command2. Then we use Get to read in the number and store it in a new variable, varinput. F inal ly we display the newly read-in variable in a text box, Text2, and close the file:

Private Sub Command2_Cl ick( )Dim varinput As Double

On Error GoTo Fi leErrorOpen “C:\binary.dat” For Binary As #1Get #1, , varinputText2.Text=Str(varinput)Close #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Accessing any Record in a Random Access File

When you’ve setup a file to hold records by creating it in Random mode with the Open statement and passing the length of the records you want to open, you can use Get to access any record in the file by record number

Get #1, recordnumber, variablename

In this case, we’re reading record number recordnumber from file 1 and placing the data read into a variable named variablename. In the same way, you can write any record with Put:

Put #1, recordnumber, variablename Using Get and Put in this way, you can read and write any record in the file.

Closing A File

You use the Close Statement to c lose the file. Closing file writes al l data out to disk. To close al l fi les your appl ication has open, just use the Close statement without any arguments.

Eg:Close #1

Saving Files from Rich Text Boxes

You can use the SaveFi le( ) method to save the text in a r ich text box to disk, and doing that is real ly easy-you just use SaveFi le( ) this way:

RichTextBox.SaveFile(pathname, [filetype])

You can save text as pla in or RTF text; the sett ings for filetype are

rtfRTF-0 (the default); the r ich text box control saves its contents as an RTF file.RtfText-1; the r ich text box control saves its contents as a text file.

Here’s an example where we display some text in a r ich text box:

Private Sub Form_Load( )RichTextBox1.Text=”This is the text in the file”

End Sub

Next, we save that text to a file this way:

Private Sub Command1_Cl ick( )RichTextBox1.SaveFi le (“C:\data.txt”)

End Sub

Page 147: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 147

Opening Files in Rich Text Boxes

You can write files to disk from a r ich text box with SaveFi le( ) . You use LoadFi le() to read files back in. you can load plain text or rt f text files.

RichTextBox.LoadFile pathname, [filetype]

For example we use the fol lowing code to load the file we wrote in previous section

Private Sub Command1_Cl ick()RichTextbox1.LoadFi le “C:\data.txt”

End Sub

Saving Files from Picture Boxes

You can use SavePicture to save the images in picture boxes to disk files.

SavePicture picture, stringexpression

Here’s what the arguments in that statement mean:

Picture-Picture or image control from which the graphics file is to be createdStringexpression-Fi lename of the graphics file to save

Note that SavePicture only saves images in BMP, WMF, and ICO formats. I f the image came from a GIF or JPEG file, i t ’s saved in BMP format. Graphics in an Image property are always saved as bitmap (BMP) files no matter what their or iginal format.

Here’s an example where we save the image from Picture1 to a file, image.bmp, when the user cl icks a button:

Private Sub Command1_Cl ick( )SavePicture Picture1.Picture, “C:\ image.bmp”

End Sub

Opening Files in Picture boxes

You use the Picture property to open images in picture box. A p icture box is ver versati le and can display images from bitmap (.bmp), icon (. ico), metafile ( .wmf), JPEG ( . jpg) , or GIF ( .gi f) files-just load the file’s name into the Picture property. You can use the LoadPicture() to load in a picture l ike this

Private Sub Command1_Cl ick( )Picture1.Picture=LoadPicture(“C:\vbvbvb\pictures\abc.bmp”)

End Sub

Using the Drive List Box, Dir List Box, and File List Box Controls

You can use the Visual Basic file controls: dr ive l ist box, the directory l ist box, and the file l ist box. These controls are intr insic to Visual Basic.

Sub Drive1_Change( )Dir1.Path=Drive1.Drive

End Sub

Sub Dir1_Change( )Fi le1.Path=Dir1.Path

End Sub

Sub Fi le1_Cl ick( )Picture1.Picture=LoadPicture(Fi le1.Path & “\” & Fi le1.Fi lename)

End Sub

You can set the pattern property of a Fi le List box to determine the type of file to d isplay in the file l ist.

You can use other controls l ike Text box to display the contents of text file

For Example the fol lowing example displays the contents of selected text file in a Text box control .

Page 148: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 148

Sub Command1_Cl ick( )Dim Fi lename As Str ingOn Error GoTo Fi leError

If (Right$(Dir1.Path,1) = “\”) ThenFi lename=File1.path & Fi le1.Fi lename

ElseFi lename=File1.Path & “\” & Fi le1.Fi leName

End I f

Open Fi leName For Input As #1Text1.Text- Iput$(LOF(1), #1)Close #1Exit Sub

Fi leError:MsgBox “Fi le Error”

End Sub

Creating and Deleting Directories

You can create a new directory with the MkDir statement and remove a directory with the RmDir statement. The fol lowing example creates a directory when the user Cl ick a Command Button

Private Sub Command1_Cl ick( )MkDir “C:\data”

End Sub

To remove the directory use RmDir statement

Private Sub Command2_Cl ick( )RmDir “C: \Data”

End Sub

Changing Directories

To change the default directory, use ChDir. Here’s an example where we change the default d irectory to C: \Windows using Chdir when the user c l icks a command button Command1.

Private Sub Command1_Cl ick ( )ChDir “C:\Windows”

End Sub

Copying a File

You can copy files using the Visual Basic Fi leSystemObject. This object provides you with access to the computer’s file system and has methods l ike CopyFi le to copy a file:

FileSystemObject.CopyFile source, destination[, overwrite]

Here, source is the source file name including path, destination is the destination file name also including path, and overwrite is a boolean that, i f True, means you want to overwrite the destination file i f i t already exists. You can use wi ldcards the asterisk [*].

CopyFi le solves a tedious problem for the programmer- i f a l l you want to do is copy a file, why should you have to write al l the code specifical ly to do that? You don’t; using CopyFi le. Here’s an example where we copy a file, file.txt, to file2.txt. Not ice that we must first create a Fi leSystemObject.

Pr ivate Sub Command1_Cl ick( )Dim Fi leSystemObject As ObjectSet Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Fi leSystem.Object.CopyFi le “C:\file.txt”, “C:\file2.txt”

End Sub

You can also do the same thing with the Visual Basic Fi leObject, where we use GetFi le to get a Fi leObject object and then use the Fi leObject’s Copy method:

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, F i leObject As ObjectSet Fi leSystemObject = CreateObject(“Scripting.Fi leSystemObject”)Set Fi leObject=Fi leSystemObject.GetFi le (“C:\file.txt”)Fi leObject.Copy “C:\file2.txt”

End Sub

Page 149: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 149

Moving a File

The Visual Basic Fi leSystemObject lets you move a file from one directory to another using its MoveFi le method. This method takes only two arguments, the source and destination paths. Here’s an example where we move a file, file.txt, from C: to the D: drive; note that we must first create a Fi leSystemObject.Pr ivate Sub Command1_Cl ick( )

Dim Fi leSystemObject As ObjectSet Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Fi leSystemObject.MoveFi le “C:\Fi le.txt”, “D:\file.txt”

End Sub

You can also do the same thing with the Visual Basic Fi leObject, where we use GetFi le to get a Fi leObject and then use the Fi leObject’s Move method:

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, F i leObject As ObjectSet Fi leSystemObject = CreateObject(“Scripting.Fi leSystemObject”)Set Fi leObject = Fi leSystemObject.GetFi le(“C:\file.txt”)Fi leObject.Move “D:\file.txt”

End Sub

Deleting a File

The Visual Basic F i leSystemObject lets you delete a file using its DeleteFi le method:

FileSystemObject.DeleteFile filespec [,force]

Here, the filespec is the file you want to delete, and force is a Boolean that, i f True, means you want to delete read-only files as wel l . Let’s see an example. Here we delete the file file.txt, from the C: drive; note that we must first create a Fi leSystemObject:

Private Sub Command1_Cl ick( )Dim Fi leSystemObject As ObjectSet Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Fi leSystemObject.DeleteFi le “C:\Fi le.txt”

End Sub

You can also do the same thing with the Visual Basic Fi leObject, where we use GetFi le to get a Fi leObject and then use the Fi leObject’s Delete nmethod:

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, F i leObject As ObjectSet Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Set Fi leObject=Fi leSystemObject.GetFi le(“C:\file.txt”)Fi leObject.Delete

End Sub

To get the Date a File Created, Modified or Last Accessed

You can use Visual Basic Fi leObject to determine when a file was created, last modified, and last accessed. The propert ies that are important here are DateCreated, DateLastModified, and DateLastAccessed.

Here’s an example how to get these dates.

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, F i leObject As ObjectSet Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Set Fi leObject=Fi leSystemObject.GetFi le(“C:\file.dat”)

Text1.Text=”C:\file.dat” &vbCrLf & “was created “ & _Fi leObject.DateCreated & vbCrLf & “was last modified “ & _Fi leObject.DateLastModified & vbCrLf & “was last accessed “ & _Fi leObject.DateLastAccessed & vbCrLf

End Sub

Creating TextStreamYou can use TextStream objects to work with text files in Visual Basic. For example, you create a text stream with the CreateTextFi le method:

FileSystemObject.CreateTextFile(filename[, overwrite[, unicode]])

Here’s what the arguments we pass to CreateTextFi le mean:

filename-Str ing which identifies the file to create oversrite-Boolean value that indicates i f an exist ing file can be overwritten. The

value is True i f the file can be oversrit ten; False i f i t can’t be overwritten. I f omitted, exist ing files are not overwritten.

Unicode-Boolean value that indicates whether the file is created as a Unicode or an ASCI I file. The value is True is created as a Unicode file; False i f i t ’s created as an ASCI I file. I f omitted, an ASCI I file is assumed.

Page 150: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 150

Here’s an example where we create a TextStream object corresponding to a file named file.txt

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, TextStream As Object

Set Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Set TextStream=FileSystemObject.CreateTextFi le(“C:\file.txt”, True)

End Sub

Opening a TextStream

To open a TextStream, you use the Fi leSystemObject’s OpenTextFi le method:

FileSystemObject.OpenTextFile(filename[, iomode[, create[, format]]])

Here are what the arguments to OpenTextFi le mean:

filename-The file to open iomode-Indicates input/output mode. Can be one of two constants, either

ForReading or ForAppending create-Boolean value that indicates whether a new file can be created i f the

specified file doesn’t exist . The value is True i f a new file is created; False i f i t isn’t created. The Default is False.

Format-One of three values used to indicate the format of the opened file. I f omitted, the file is opened as ASCII

Here’s an example where we open a TextStream object corresponding to a file named file.txt

Private Sub Command2_Cl ick( )Dim Fi leSystemObject, TextStream As Object

Set Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Set TextStream=FileSystemObject.OpenTextFi le(“C:\file.txt”)

End Sub

Writing to a TextStream

To write to a TextStream object, you use one of these methods:

Write(string)

WriteLine([string])

Here’s an example where we create a file named file.txt and write a str ing, “here is some text” to that file. F irst, we create a new TextStream: then we write our l ine of text to the file and close that file:

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, TextStream As Object

Set Fi leSystemObject = CreateObject(“Scripting.Fi leSystemObject”)Set TextStream =Fi leSystemObject.CreateTextFi le(“C:\file.txt”, True)

TextStream.WriteLine (“Here is some text”)TextStream.Close

End Sub

Reading From a TextStream

To read from a TextStream Object, you use one of these methods; note that the Read method lets you specify how many characters to read:

Read(numbercharacters)

ReadAll

ReadLine

Each of these methods returns the text read. Let’s see an example. Here we’l l open a file, file.txt, and one l ine from it, displaying that l ine in a text box. First we create TextStream object for that file: next we use the ReadLine method to read a l ine from the file and display it in a text box, Text1, and close the TextStream:

Page 151: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 151

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, TextStream As Object

Set Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Set TextStream=FileSystemObject.OpenTextFi le(“C:\file.txt”)

Text1.Text=TextStream.ReadLineTextStream.Close

End Sub

Closing a TextStream

You use Close method to close a TextStream object . In the fol lowing example, we write to a file, file.txt, using a TextStream object and then close that TextStream using Close

Private Sub Command1_Cl ick( )Dim Fi leSystemObject, TextStream As Object

Set Fi leSystemObject=CreateObject(“Scripting.Fi leSystemObject”)Set TextStream=FileSystemObject.CreateTextFi le(“C:\file.txt”, True)

TextStream.WriteLine (“Here is some text”)TextStream.Close

End Sub

Page 152: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 152

Chapter 28

Working with GraphicsThere are two principal ways of drawing graphics in Visual Basic: using graphic methods, such as the one’s we’ l l see here and using graphics controls l ike l ine and shape controls. Graphic methods work wel l in s ituations where using graphical controls requires too much work. For example, creating grid l ines on a graph would require an array of l ine controls but only a small amount of code using the Line method. In addit ion, when you want an effect to appear temporari ly, you can write a couple of l ines of code for this temporary effect instead of using another control . Also, graphics methods offer some visual effects that are not avai lable in the graphical controls. For example, you can only create arcs or paint individual pixels using the graphics methods.

Visual Basic CoordinatesVisual Basic coordinate systems have the origin (0,0) at upper left and are specified as (x,y), where x is horizontal and y is vert ical . wHen we draw graphics in Visual Basic, we’l l be using this coordinate system. For forms the origin is the upper left of form’s cl ient area-the part that excludes borders, menu bars, and so on. The default unit of measurement in Visual Basic is twips, which is approximately 1/1440 of an inch. You can also change to other measurement units l ike mil l imeters, inches, and so on.

AutoRedraw and Paint

One of the Visual Basic’s most popular aspects is that you can make a form or control redraw itself as needed by sett ing its AutoRedraw property to True. However, sett ing AutoRedraw to True can use a lot of system resources, no tably memory, and you might not want to do so in al l cases. I f not, you can use the Paint event to redraw your graphics, because this event occurs everytime a form or control l ike a picture box is drawn or redrawn.

Here’s an example. In this case, we draw a circ le inscribed in the smaller dimensions of a form when the form is drawn

Private Sub Form_Paint()Form1.Circle (ScaleWidth /2 , ScaleHeight / 2), _

Switch(ScaleWidth >= ScaleHeight, ScaleHeight/2, _ScaleWidth < ScaleHeight, ScaleWidth / 2)

End Sub

Clearing the Drawing Area

One of the first things to learn about drawing graphics is how to c lear the drawing area. You do that with the Cls method, which redraws the form or control in the current BackColor. Here’s an example where we clear a picture box, P icture1, when the user cl icks that picture box:

Private Sub Picture1_Cl ick()Picture1.Cls

End Sub

Setting Colors

Here are some commonly used properties you can specify colors for and what they mean:

BackColor - The Background color of the control or form ForeColor - The drawing color used to draw figures and text. BorderColor - The Color of the Border FillColor - The Color you want the figure filled with

To set color properties l ike these in Visual Basic, you need to know how to set colors in general . There are four ways to do that:

Using the RGB function Using the QBColor function to choose one of 16 Microsoft Quickbasic colors Using one of the intr insic Visual Basic color constants Entering a color value direct ly

The RGB funct ion takes three color values, 0 to 255, to specify the red, green, and blue values in the color you want l ike this: RGB(RRR, GGG, BBB) , where RRR, GGG and BBB are the red, green, and blue color values, respectively. For example

RGB(255, 0, 0) RedRGB(0, 255, 0) GreenRGB(0, 0, 255) BlueRGB(255, 255, 255) WhiteRGB(0, 0, 0) Black

Page 153: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 153

The QBColor function returns one of these colors when you pass it the matching numbers, 0 to 15: Black-0 Blue-1 Green-2 Cyan-3 Red-4 Magenta-5 Yel low-6 White-7 Gray-8 Light Blue-9 Light Green-10 Light Cyan-11 Light Red-12 Light Magenta-13 Light Yel low-14 Light White-15

You can also use one of the bui lt- in Visual Basic color constants, l ike vbRed, to specify a color. The standard Visual Basic color constants appear in the fol lowing Table

Constant Value Description

VbBlack &H0 BlackVbRed &HFF RedVbGreen &HFF00 GreenVbYel low &HFFF Yel lowVbBlue &HFF0000 BlueVbMagenta &HFF00FF MagentaVbCyan &HFFFF00 CyanVbWhite &HFFFFFF White

System Color constants

Constant Value Description

VbScrol lbars &H80000000 Scrol l bar colorVbDeskTop &H80000001 Desktop colorVbActiveTit lebar &H80000002 Color of the t i t le bar for the act ive windowVbInactiveTit leBar &H80000003 Color of the t i t le bar for the inact ive windowVbMenuBar &H80000004 Menu background colorVbWindowBackground &H80000005 Window background colorVbWindowFrame &H80000006 Window Frame colorVbMenuText &H80000007 Color of Text on MenusVbWindowText &H80000008 Color of Text in WindowsVbTit leBarText &H80000009 Color of text in caption, s ize box, and scrol l arrowVbActiveBorder &H8000000A Border color of Act ive windowVbInactiveBorder &H8000000B Border color of inactive windowVbAppl icationWorkspace &H8000000C Background color of mult iple document interfaceVbHighLight &H8000000D Background color of i tems selected in a controlVbHighl ightText &H8000000E Text Color of i tems selected in a controlVbButtonFace &H8000000F Color of shading on the face of command buttonsVbButtonShadow &H80000010 Color of shading on the edge of command buttonsVbGrayText &H80000011 Grayed (disabled) TextVbButtonText &H80000012 Text color on Puch buttonsVbInactiveCaptionText &H80000013 Color of text in an inact ive captionVb3DHighLight &H80000014 Highl ight color for 3D display elementsVb3DDKShadow &H80000015 Darkest shadow color for 3D display elementsVb3Dlight &H80000016 Second l ightest of the 3D colors after vb3Dhighl ightVb3Dface &H8000000F Color of text faceVb3Dshadow &H80000010 Color of text shadowVbInfoText &H80000017 Color of Text in tool t ips

You can also specify colors as 4-byte integers directly, i f you want to. The range for ful l RGB colors is 0 to 16,777,215 (&HFFFFFF&). The high byte of a number in this range equals 0. The lower 3 bytes, from least to most s ignificant byte, determine the amount of red, green, and blue. The red, green, and blue components are each represented by a number between 0 and 255 (&HFF). This means that you can specify a color as a hexadecimal number l ike this: &HBBGGRR&

Drawing Text

You can display text in forms and picture boxes with the Print method.

[object.]Print [outputlist] [{ ; | , }]

The upper- left corner of the text you print appears at the location CurrentX,CurrentY. CurrentX and CurrentY are properties of forms or picture boxes. I f you want to print mult iple i tems on different l ines, separate them with commas. I f you want to print mult iple i tems on the same l ine, separate them with semicolons. Let’s see an example. Here, we draw text start ing at the center of both a form and a picture box, Pciture1. To

Page 154: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 154

draw graphics from the Form Load event, you must set the form and picture box’s AutoRedraw property to True.

Private Sub Form_Load( )CurrentX=ScaleWidth / 2CurrentY=ScaleHeight / 2Print “Hel lo from ICES”

Picture1.CurrentX=Picture1.ScaleWidth / 2Picture1.CurrentY=Picture1.ScaleHeight / 2Picture1.Print “Hel lo from ICES”

End Sub

You can format text when you print i t to forms, p icture boxes, or the printer object by determining its width and height, and you do that with the TextWidth and TextHeight methods.

Working with Fonts

You have a lot of formatting options when working with text. In particular, you can use these font properties in forms and picture boxes.

FontBold FontItal ic FontName FontSize FontStr ikeThru FontTransparent FontUnderLine

For example, we set the font in a form to bold and the font size to 12 in a picture box this way. To draw graphics from Form Load event, you must set form and picture box’s AutoRedraw property to True.

Private Sub Form_Load( )CurrentX=ScaleWidth / 2CurrentY=ScaleWidth / 2

FontBold=TruePrint “Hel lo from Hel lo Visual Basic”

Picture1.CurrentX=Picture1.ScaleWidth / 2Picture1.CurrentY=Picture1.ScaleHeight / 2Picture1.FontSize =12Picture1.Print “Hel lo From ICES”

End Sub

The Font Object

You can also create a Font object that holds al l the properties of a font; here are the font object’s properties

Bold I tal ic Name Size StrikeThrough Underl ine Weight

To create a Font object, you dimension it as a new object of type StdFont. For example, here’s how we instal l 24-point Arial as the font in a text box, using Font object.

Pr ivate Sub Command1_Cl ick( )Dim Font1 As New StdFontFont1.Size=24Font1.Name=”Arial”Set Text1.Font=Font1

End Sub

You can also determine which fonts are avai lable for either screen or printer by checking the Fonts property of the Visual Basic Pr inter and Screen objects. This property holds an array of the avai lable font’s names. For example, to see al l the fonts avai lable on your display using Visual Basic, you can loop over al l fonts in the Screen object-the total no. of fonts is stored in FontCount property- and display the font names in a combo box.

Private Sub Form_Load( )Dim intLoopIndex As Integer

For intLoopIndex=0 to Screen.FontCount-1Combo1.AddItem Screen.Fonts(IntLoopIndex)

NextEnd Sub

Page 155: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 155

Drawing Lines

You draw l ines in forms and picture boxes with the Line method.

Object.Line [Step] (x1,y1) [Step] (x2,y2) , [color], [B][F]

Here are the arguments you pass to Line

Step-Keyword specifying that the start ing point coordinates are relat ive to the current graphics posit ion given by the CurrentX and CurrentY properties

X1,y1-Single values indicating the coordinates of the start ing point for the l ine or rectangle. The ScaleMode property determines the unit of measure used. I f omitted, the l ine begins at the posit ion indicated by CurrentX and CurrentY.

Step-Keyword specifying that the end point coordinates are relative to the l ine start ing point

X2,y2-Single values indicating the coordinates of the end point for the l ine being drawn.

Color-Long integer value indicating the RGB color used to draw the l ine. I f omitted, the ForeColor property sett ing is used. You can use the RGB function or QBColor function to specify the color.

Color-Long integer value indicating the RGB color used to draw the l ine. I f omitted, the Forecolor property sett ing is used. You can use the RGB funct ion or QBColor function to specify the color.

B-I f included, causes a box to be drawn using the coordinates to specify opposite corners of the box.

F-I f the B option is used, the F opt ion specifies that the box is fil led with the same color used to draw the box. You cannot use F without B. I f B is used without F, the box is fil led with the current Fi l lColor and Fi l lStyle. The default value for Fi l lSty le is transparent.

Let’s see an example. Here, we’ l l draw l ines cr isscrossing a form and a picture box, Picture1.

Private Sub Command1_Cl ick( )Line (0, 0) – ScaleWidth, ScaleHeight)Line (ScaleWidth, 0) – (0, ScaleHeight)

Picture1.Line (0, 0)-P icture1.ScaleWidth, P icture1.ScaleHeight)Picture1.Line (Picture1.ScaleWidth, 0)-(0, P icture1.ScaleHeight)

End Sub

Drawing Boxes

You can draw boxes in forms and picture boxes with the Line method, using the B argument.

Object.Line [step] (x1,y1) [step] (x2,y2), [color], [B][F]

Lets see an example to draw a box in a form.

Private Sub Command1_Cl ick( )Line (ScaleWidth / 4, ScaleHeight / 4)-(3*ScaleWidth / 4, 3 * _

ScaleHeight / 4), , BEnd Sub

Drawing Circles

You use the Circ le method to draw circles in forms and pictures:

Object.circle [step] (x,y), radius, [color, [start, end, [aspect]]]

Here are the arguments you pass to Circ le

Step-Keyword specifying that the center of the circ le, e l l ipse, or arc is relative to the current coordinates given by the CurrentX and CurrentY properties of object.

X,y-Single values indicating the coordinates for the center point of the c ircle, el l ipse, or arc. The ScaleMode property of object determines the units of measure used.

Radius-Single value indicat ing the radius of the circ le, e l l ipse, or arc. The ScaleMode property of object determines the unit of measure used.

Color-Long integer value indicating the RGB color of the circ le’s outl ine. I f omitted, the value of the ForeColor property is used. You can use the RGB function or QBColor function to specify the color.

Start ,end-Single-precis ion values. When an arc or a part ial c ircle or el l ipse is drawn, start and end specify ( in radians) the beginning and end posit ions of the arc. The range for both is -2pi radians to 2pi radians. The default value for start is 0 radians; the default for end is 2*pi radians.

Aspect-Single-precis ion value indicating the aspect ratio of the circ le. The default value is 1.0, which yields a perfect (nonel l ipt ical) circ le on any screen.

Page 156: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 156

As an example, we draw the biggest c ircle possib le in both a form and a picture box, Picture1, when the user c l icks a Command button using the code below and using Switch function to determine i f the form’s width or height is larger.

Private Sub Command1_Cl ick( ) Circle (ScaleWidth / 2, ScaleHeight / 2), _

Switch(ScaleWidth >= ScaleHeight, ScaleHeight / 2, _ScaleWidth < ScaleHeight, ScaleWidth / 2)

Picture1.Circle (P icture1.ScaleWidth / 2, Picture1.ScaleHeight / 2) , _Switch(Picture1.ScaleWidth >= Picture1.ScaleHeight, _Picture1.ScaleHeight / 2, P icture1.ScaleWidth < _Picture1.ScaleHeight, Picture1.ScaleWidth / 2)

End Sub

Drawing Ell ipses

You use the Circ le method to draw el l ipses in picture boxes and forms, sett ing the aspect argument to set the el l ipse’s aspect ratio:

Object.circle [step] (x,y), radius, [color, [start, end, [aspect]]]

The aspect ratio is the ratio of the vertical to horizontal axes in the el l ipse, and the length of the el l ipse’s major (that is longer) axis is the value you specify in the radius argument. Here’s an example, where we use a vert ical to horizontal rat io of 0.8 for the el l ipse.

Private Sub Command1_Cl ick( )Circle (ScaleWidth / 2, ScaleHeight / 2), _

Switch(ScaleWidth >= ScaleHeight, ScaleHeight / 2, _ScaleWidth < ScaleHeight, ScaleWidth / 2), , , , 0.8

End Sub

Drawing Arcs

You use the Circ le method to draw arcs, using the start, end , and aspect arguments:

Object.Circle [Step] (x,y), radius, [color, end, [aspect]]]

In Visual Basic, an arc is part of an el l ipse. To draw an arc, you proceed as though you were going to draw an el l ipse, including specifying the origin, major radius, color, and aspect ratio. Then you specify values for the beginning and end of the arc, in radians.

Here’s an example to draw a convex arc in a form and a concave arc in a picture box

Private Sub Command1_Cl ick( )

Circle (Scalawidth / 2, ScaleHeight / 2), _Switch(ScaleWidth >= ScaleHeight, ScaleHeight / 2, _ScaleWidth < ScaleHeight, ScaleWidth / 2), , 0, 3.14, 0.8

Picture1.Circle (P icture1.ScaleWidth / 2, Picture1.ScaleHeight / 2) , _Switch(Picture1.ScaleWidth >= Picture1.ScaleHeight. _Picture1.ScaleHeight / 2, P icture1.ScaleWidth < _Picture1.ScaleHeight, Picture1.ScaleWidth / 2), , 3.14, 6.28, 0.8

End Sub

Drawing Freehand with the Mouse

As the user moves the mouse, you can use the Line statement to connect the mouse locations passed to your program in the MouseMove event handler. Note that you are not passed every pixel the mouse travels over, so you must connect the dots, so to speak, rather than sett ing individual pixels as a lot of programmers think.

Here’s an example where we draw freehand with the mouse.

Create a boolean variable in general declaration sect ion and set i ts init ial value to False

Dim blnDrawFlag As Boolean

Private Sub Form_Load()BlnDrawFlag=False

End Sub

When the user presses the mouse button, we set the current drawing locat ion (CurrentX,CurrentY) to the locat ion of the mouse and set b lDrawFlag to True in the MouseDown event handler.

Pr ivate Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

CurrentX=XCurrentY=Y

Page 157: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 157

BlnDrawFlag=TrueEnd Sub

When the user moves the mouse, we check i f the blnDrawFlag is True in MouseMove event, and i f so, draw a l ine from the current drawing location to the current (X,Y) posit ion.

Private Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

If blnDrawFlag Then L ine –(X,Y)End Sub

When the mouse button goes up, we set blnDrawFlag to False in MouseUp event handler

Private Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)

BlnDrawFlag=FalseEnd Sub

Fill ing Figures with Color

To fil l figures with color, you can use the Fi l lColor property of forms and picture boxes, along with the Fi l lStyle property to set the type of fil l you want.

Let ’s see an example. Here we’ l l draw a circ le and a box in a form in the default drawing color and fil l those figures with sol id blue when the user c l icks a button, Command1. First , we set the form’s Fi l lColor property to Blue

Private Sub Command1_Cl ick( )Fi l lColor=RGB(0,0,255)Fi l lStyle=vbFSSol idLine (0,0)-(ScaleWidth / 2, ScaleHeight / 2), , BCircle (3 * ScaleWidth / 4, 3 * ScaleHeight / 4), ScaleHeight / 4

End Sub

Fill ing Figures with Patterns

You can use the form and picture boxes Fi l lStyle property to set the fil l pattern in Visual Basic graphics. Here are the possibi l i t ies

VbFSSol id-0; so l id VbFSTransparent-1 (the default); transparent VbHorizontalLine-2; horizontal l ine VbVert icalL ine-3; vert ical l ine VbUpWardDiagonal-4; upward Diagonal VbDownwardDiagonal-5;downward diagonal VbCross-6; cross VbDiagonalCross-7; diagonal cross

Setting Figure Drawing Style and Drawing Width

Set the DrawStyle property in forms or picture boxes to change the l ine styles. Here are the possible values.

vbsol id-1 (the default); so l id (the border is centered on the edge of shape) vbDash-2;dash vbDot-3;dot vbDashDot-4;dash-dot vbDashDotDot-5; dash-dot-dot vbInvisible-5; invis ible vbInsideSol id-6; inside sol id (the outter edge of the border is the outter edge of

figure)

you can also set the drawing width with DrawWidth property

Eg:Private Sub Command1_Cl ick( )

DrawStyle=vbDashLine(0,0)-(ScaleWidth / 2, ScaleHeight / 2), ,BCircle( (3 * ScaleWidth / 4, 3 * ScaleHeight / 4) , ScaleHeight / 4

End Sub

Page 158: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 158

Drawing Points

To draw individual points, you use Pset in forms and picture boxes l ike this:

Object.Pset [Step] (x,y), [color]

Here are the arguments you pass to Pset:

Step-keyword specifying that the coordinates are relative to the current graphics posit ion given by the CurrentX and CurrentY properties

X,y-Single values indicating the horizontal (x-axis) and vertical (y-axis) coordinates of the point to set.

Color-Long integer value indicating the RGB color specified for the point. I f omitted, the current ForeColor property sett ing is used. You can use the RGB function or QBColor function to specify the color.

You can also use the Point method to retr ieve the color of a point at a specific (x,y) location.

Setting The Drawing Mode

You draw with pens in Windows. Every drawing operation uses these pens. When you set the drawing width, you’re real ly sett ing the width of the pen; when you set the drawing color, you’re sett ing the color of the pen.

You can also use the DrawMode property to specify how the current pen interacts with the graphics i t already finds in a form or picture box. Here are the possible sett ings for the pen’s drawing mode:

vbBlackness-1, Blackness vbNotMergePen-2,Not Merge Pen; inverse of sett ing 15(Merge Pen) vbMaskNotPen-3,Mask Not Pen; combinat ion of the colors common to the

background color and the inverse of the pen vbNotCopyPen-4, Not Copy Pen; inverse of sett ing 13 (Copy Pen) vbMaskPenNot-5, Mask Pen Not; combination of the colors common to both the pen

and the inverse of the display vbInvert-6, Invert; inverse of the display color vbXorPen-7, XOR Pen; combination of the colors in the pen and in the display color,

but not in both vbNotMaskPen-8, Not Mask Pen; inverse of sett ing 9 (Mask Pen) vbMaskPen-9, Mask Pen; combination of the colors common to both the pen and the

display vbNotXorPen-10, Not XOR Pen; inverse of sett ing 7 (XOR Pen) vbNop-11 Nop, No operation; output remains unchanged ( in effect, this sett ing

turns drawing off) vbMergeNotPen-12, Merge Not Pen, combination of the display color and the

inverse of the pen color vbCopyPen-13, Copy Pen (the default); color specified by the ForeColor property vbMergePenNot-14, Merge Pen Not; combination of the pen color and the inverse of

the display color vbMergePen-15, Merge Pen; combination of the pen color and the display color vbWhiteness-16, Whiteness

For example, we can set the pen to be an invert pen with this code and draw over some l ines. The pen wi l l invert the pixels i t finds:

Private Sub Form_Load()

Dim intLoopIndex As Integer

For intLoopIndex = 1 to 9DrawWidth=intLoopIndexLine (0, intLoopIndex * ScaleHeight / 10)-(ScaleWidth, _

IntLoopIndex * ScaleHeight / 10)Next

DrawMode=vbInvertDrawWidth=10Line (0,0)-(ScaleWidth, ScaleHeight)Line (0, ScaleHeight)-(ScaleWidht,0)

End Sub

Setting Drawing Scales

Forms and Picture boxes have a number of scale propert ies, and perhaps the most popular one is ScaleMode, which sets the units of measurement in a picture box. Here are the possible values for ScaleMode. Note that when you set the scale mode, al l measurements are in those new units, including coordinates passed to your program, l ike mouse down locations.

Page 159: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 159

vbUser-0; indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop propert ies are set to custom values.

VbTwips-1 (the default); twip (1/1440 per logical inch) VbPoints-2; point (72 points per logical inch) VbPixels-3; pixel (smallest unit of monitor or printer resolut ion) VbCharacters-4; character (horizontal equals 120 twips per unit ; vert ical equals

240 twips per unit) VbInches-5; inch VbMil l imeters-6; mil l imeter VbCentimeters-7; centimeter VbHimetric-8; Himetric VbContainerPosit ion-9; units used by the control ’s container to determine the

control ’s posit ion VbContainerSize-10; units used by the control ’s container to determine the

control ’s s ize

If you set the scale mode to vbUser, you can define your own units by sett ing the dimensions of the picture box using the ScaleLeft, ScaleTop, ScaleWidth, and ScaleHeight properties.

Using the Screen Object

The Visual Basic Screen object offers you a lot of information about the current display. Here are that object’s properties

TwisPerPixelX-Twips per pixel horizontal ly TwipsPerPixelY-Twips per pixel vert ical ly Height-Screen Height Width-Screen Wisth Fonts-Col lection of names of the avai lable fonts FontCount-Total number of screen fonts avai lable ActiveControl-Currently act ive control ActiveForm-Currently active form MouseIcon-Returns or sets a custom mouse icon MousePointer-Returns or sets a value indicat ing the type of mouse pointer

displayed when the mouse is over a particular part of an object at runt ime

Resizing Graphics When the Window is Resized

You can use the ReSize event to catch window or picture box resizes. For example, here we add a New subroutine, DrawBox to a Form which draws a rectangle to a form.

Private Sub DrawBox()Line (ScaleWidth / 4, ScaleHeight / 4)-(3 * ScaleWidth / 4, 3 * ScaleHeight /4), , B

End Sub

We can cal l DrawBox in the Load event to draw the box the first t ime. Set AutoRedraw property to True to draw graphics in the Form Load event.

Private Sub Form_Load( )

DrawBoxEnd Sub

When the user resizes the form, we clear the form and redraw the box in the Form Resize event

Private Sub Form_Resize ( )ClsDrawBox

End Sub

Printing Graphics

Visual Basic has two ways of printing both text and graphics

Printing ent ire form using PrintForm method Printing with the Printer object and using graphical methods as wel l as the

NewPage and EndDoc methods

The PrintForm method

The PrintForm method sends an image of a given form to the printer, complete with menu bar, t i t le bar, , and so on. To print information from your appl ication with PrintForm, you must first display that information on a form and then print that form with the PrintForm method l ike this

[form].PrintForm

The Printer Object

Page 160: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 160

The Printer Object represents the default pr inter and supports text and graphics methods l ike Print, Pset, L ine, PaintPicture, and Circle. You use these methods on the Printer Object as you would on a form or picture box. The Printer object also has al l the font properties we’ve seen earl ier.

When you finish placing the information on the Printer object , you use the EndDoc method to send the output to the Printer. You can also print mult iple page documents by using NewPage method on the Printer Object. When appl ications c lose, they automatical ly use the EndDoc method to send any pending information on the Printer object.

The Printers Collection

The Printers col lect ion is an object that contains al l the printers that are avai lable, and each printer in the col lection has a unique (0-based) index for identificat ion. For example, we select the first printer from the Printers col lection to be the current printer by loading that printer into the Printer object.

Pr ivate Sub Command1_Cl ick( )Set Pr inter=Printers(0)

End Sub

Layering Graphics with the AutoRedraw and ClipControls Properties

When you create graphics in Visual Basic, bear in mind that graphical controls and labels, non graphical controls, and graphics methods appear on different layers. The behavious of these layers depends on three things. The AutoRedraw property, the Cl ipControls property, and whether graphics methods appear inside or outside the Paint event. Usual ly the layers of a form or other container are as fol lows.

Front layer-Nongraphical controls l ike command buttons, checkboxes, and file controls.

Middle layer-Graphical controls and labels Back layer- Drawing space for the form or container. This is where the results of

graphics methods appear

Anything in one layer covers anything in the layer behind it , so graphics you create with graphical controls appear behind other controls on the form, and al l graphics you create with the graphics methods appear below al l graphical and nongraphical controls. Combining sett ings for AutoRedraw and Cl ipControls and placing graphics methods inside or outside the Paint event affects layering and the performance of the appl icat ion.

Page 161: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 161

Chapter 29Error Handling

Chapter 30

Windows API

Page 162: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 162

Chapter 31

Creating ActiveX controls and DocumentsActiveX controls and Act iveX documents are two of the ActiveX components you can bui ld in VISUAL BASIC. The whole ActiveX field started original ly to differentiate controls designed for internet usage from general OLE (Object L inking and Embedding) controls. Int ime, however, al l OLE controls have come to be referred to as ActiveX controls. In fact , the field has taken off so vigorously that now VISUAL BASIC can bui ld not just ActiveX controls in VISUAL BASIC, but ActiveX documents.

In programming terms al l ActiveX components are real ly OLE servers, but that doesn’t help us understand what’s going on. I t ’s better to break things down and look ate the three types of ActiveX components

ActiveX Controls ActiveX Documents Code Components (OLE automation servers)

ActiveX Controls

ActiveX Controls are the controls you can add to the VISUAL BASIC toolbox using the Components dialog box. You can add those controls to a VISUAL BASIC program l ike any other control . You can also use ActiveX controls on the Internet, embedding them in your web pages, as we’ l l see when we work on creat ing Act iveX controls. ActiveX controls can support properties, methods and events.

Your ActiveX control can be bui lt entirely from scratch, i t can be bui lt on another control , or i t can contain mult iple exist ing controls. VISUAL BASIC ActiveX controls are based on the VISUAL BASIC UserControl object. When you create an ActiveX control , you create a control c lass file with the extension .ct l . VISUAL BASIC uses that file to create the actual control , which has the extension .OCX. After you register that control with Windows (you can use windows uti l i t ies l ike regsvr32.EXE to register a control) , the control wi l l appear in VISUAL BASIC components dialog box, ready for you to add to a program. You can also use these controls in Web Pages.

Creating an ActiveX ControlSelect the New Project menu item in VISUAL BASIC file menu to open the New project dialog box. Select ActiveX control i tem in new project dia log and cl ick on OK. This creates a new, empty Act iveX control . The default name of the control is Project1. Change the name using Project > Properties to ‘FirstControl ’ . Also save the project as firstcontrol .vbp. Instead of a FRM file, you save ActiveX controls in CTL files. Select the Save UserControl1 i tem in the file menu to save the control as firstcontrol .ct l . Now we have created a new ActiveX control , i t ’s t ime to make it do something.

You can design the appearance of your Act iveX control ent irely from scratch, creating an entirely new control , never seen before. In that case, you’re responsible for creating the control ’s appearance from scratch. Later, you can add events to your control , as wel l as methods and propert ies. To design the appearance of your entirely new control , you can use the VISUAL BASIC graphics methods that the UserControl object supports, such as Circle, Line, Pset, Pr int , Cls, and Point. You can also display an image in the UserControl object by sett ing its Picture property.

For Example, double c l ick on user control to open the fol lowing code window.

Private Sub UserControl_Init ial ize( )

End Sub

This function is just l ike the Form_Load procedure. Set the control ’s AutoRedraw property to True so we can draw graphics from UserControl_Init ial ize, and then draw the l ines to cr isscross the control , using the Line method and ScaleWidth and ScaleHeight.

Private Sub UserControl_Init ial ize( )Line ( 0,0 ) - ( ScaleWidth, ScaleHeight)Line ( 0, ScaleHeight ) – ( ScaleWidth , 0 )Line ( ScaleWidth / 4, ScaleWidth / 4 ) – ( 3 * ScaleWidth / 4 , _

3* ScaleHeight / 4 ) , , BFEnd Sub

Let’s test this new Act iveX control . To do that, just select the Run menu’s Start i tem. This brings the Project > Properties dia log box. Leave UserControl1 in Start component box, and make sure the Use Exist ing Browser box is cl icked, then cl ick OK. This registers our control with Windows, creates a temporary HTML page with the control embedded in i t , and starts the Internet Explorer.

You can see our new ActiveX control . It is registered with Windows and has its own ID, so this page can use HTML <OBJECT> tag to embed one of our controls in the page:

<HTML><BODY>

Page 163: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 163

<OBJECT classid=”clsid:B2A69D3B – D38C – 11D1 – 8881 – E45E08C10000”></OBJECT></BODY></HTML>

When you select End in the Run menu, VISUAL BASIC unregisters our control with Windows. To register i t permanently, use a Windows uti l i ty l ike regsvr32.EXE.

VISUAL BASIC ActiveX controls are much l ike VISUAL BASIC forms when it comes to graphics. I f you want your control to be automatical ly redrawn when needed, just set the control ’s AutoRedraw property to True, just as you would for a VISUAL BASIC form or intr insic control . You can also add your code to the control ’s Paint event.

Basing An ActiveX Control on An Existing VISUAL BASIC Control

Lets Explain i t using Example.

Create a new ActiveX Control by selecting the ActiveX control i tem in the New Project Dialog. Now draw a text box, Text1. Now set the text box’s Scrol lBars property to Both (3), and set i ts Mult iLine property to True. When the control is first displayed, we stretch the text box to cover the control this way in the ActiveX control Init ial ize event handler.

Pr ivate Sub UserControl1_Init ial ize( )

Text1.Left = 0Text1.Top = 0Text1.Width = ScaleWidthText1.Height = ScaleHeight

End Sub

Now select the Start i tem in the Run menu, c l ick on OK i f the Project Properties dialog box appears to open the control in Internet Explorer. Of course, as i t stands, our Act iveX Control is exact ly l ike a VISUAL BASIC text box, so it ’s hard to see why you’d make an ActiveX control out of i t . However, you can tai lor that control the way you want i t . For example, you can do a lot of processing behind the scenes on the text in the text box. You can also change the way the control interacts with the user.

The controls you use in an Act iveX control are cal led constituent controls, and you can handle events from those controls just as you would in a standard VISUAL BASIC program. For example, here, we’l l set up the no “L” text box. Create a new ActiveX control by selecting the ActiveX Control i tem in the New Project Dialog box. Now draw a text box, Text1. Now set the text box’s Scrol lBars property to Both(3), and set i ts Mult iLine property to True.

Add this code to the Init ial ize event handler to stretch the text box over the entire ActiveX control when the control first appears.

Private Sub UserControl1_Init ial ize( )Text1.Left=0Text1.Top=0Text1.Width=ScaleWidthText1.Height=ScaleHeight

End Sub

Now add a KeyPress event handler to the text box in the same way as in a standard VISUAL BASIC program

Private Sub Text1_KeyPress ( KeyAsci i As Integer )I f KeyAsci i=Asc(“L”) Then

KeyAsci i=0Beep

End I fEnd Sub

Now this ActiveX Control wi l l display a text box, but i t won’t let the user type the letter “L”. In this way, we’ve handled an event from a const ituent control in our ActiveX Control .

Adding Controls to an ActiveX Control ( A Calculator Act iveX Control )

Here we’l l create an ActiveX Control that is real ly a calculator that the user can use to add numbers

Create a New ActiveX Project now, giving the project name “Calculator” using Project Properties. In addit ion, change the name of the control to “CalculatorControl” in the properties window. Now when we add this control to another program using components

Page 164: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 164

dialog, this control wi l l be l isted as “Calculator”, and when we create controls of this type in that program, the first one wi l l be cal led CalculatorControl1, the next CalculatorControl2 and so on.

Add these controls in vert ical l ine in the ActiveX control: a TextBox, Text1; a label with caption “+”; another TextBox, Text2; a command button, Command1, with capt ion “=”; and a third TextBox, Text3.

Now double cl ick the command button to open its cl ick event handler and add the fo l lowing code

Private Sub Command1_Cl ick ( )Text3.Text=Str(Val (Text1.Text) + Val (Text2.Text) )

End Sub

Testing an ActiveX Control

You can test, and even debug ActiveX controls in the Internet Explorer. Just select the start i tem in the VISUAL BASIC Run menu to see the ActiveX control you’re designing at work.

Let’s see an example, here, we’l l run the Act iveX control we developed in the previous topic, the calculator control . To open this control in the Internet Explorer, select the Project menu’s Calculator Properties i tem, opening the Project Properties dialog box. Cl ick the debugging tab now.Leave the entry CalculatorControl in the Start Component box, and make sure the Use Exist ing Browser box is cl icked, then cl ick on OK. To run the control , just select the Run menu’s start i tem now. This registers our control with Windows, creates a temporary HTML page with the control embedded in i t , and starts the Internet Explorer. Now you can access the ActiveX Control .

Creating a VISUAL BASIC Project Group to Test an ActiveX Control

Create a new VISUAL BASIC standard EXE project, Project1. Select the Add Project i tem in the Fi le menu Click the Exist ing tab in the Add Project d ialog box, select the name of the ActiveX

Calculator project , and cl ick OK. This adds the Calculator ActiveX Project to the current project and creates a

program group. Select the select Project Group as item in the Fi le menu, accept ing al l default file names, including the group file i tself , group1.vbg

Close the calculator project’s window; that makes the calculator ActiveX control avai lable to us in the other project, and it wi l l appear in the toolbox.

Add a new calculator control to Form1 of Project1. Select the Run menu’s Start i tem to start Project1.

Fol lowing these steps creates the running program. Now we’re testing ActiveX controls in VISUAL BASIC.

Registering an ActiveX Control

To instal l an ActiveX Control in Windows, you must register i t with Windows, and you can do that either with the setup program or with the Window regsvr32.exe uti l i ty . Lets see an example. Here we’ l l see how to register an ActiveX Control named, say, act ivex.ocx with windows. First , use the Fi le menu’s Make activex.ocx menu item to create act ivex.ocx. Next, we’ l l use regsvr32,exe, which is usual ly found in C: \Windows\System directory, to register that control with windows. Here’s how to register an ActiveX Control .

C:\WINDOWS\SYSTEM> regsvr32 C:\VBBB\ActiveX.OCX

After the Act iveX control is registered, i t wi l l appear in the VISUAL BASIC Components Dialog Box and you can add it to the VISUAL BASIC toolbox.

Using a Custom ActiveX Control in a VISUAL BASIC Program

Now that we’ve registered our VISUAL BASIC control with Windows. You add ActiveX controls that you bui ld to VISUAL BASIC projects just as you add any other ActiveX Controls, such as the ones that come with VISUAL BASIC.

Lets use an Example.

Start a New Standard EXE project and open the VISUAL BASIC Components d ialog using Project > Components. Cl ick the Controls tab and cl ick the entry labeled Calculator in the Components dia log box to add our calculator, and c lose that dialog box to add the calculator to the VISUAL BASIC toolbox. Now draw a new calculator ActiveX Control in the program’s main form, creating the new control , CalculatorControl1 and run the program.

Adding a Property to an ActiveX Control

When we add our new custom calculator ActiveX control to a VISUAL BASIC program, as we did in the previous topic, you can see that the control already has quite a number of controls bui lt into it . We can also add our own properties to an ActiveX Control .

Page 165: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 165

For example, here we’ l l add two properties to the calculator Act iveX Control , Operand1 and Operand2, which wi l l hold the text in the top two text boxes in the Calculator, Operand1 and Operand2, which we add when the user c l icks the = button. After we add those properties, you can access them in programs that make use of our ActiveX Control just as you would any other ActiveX Control ’s properties. Here’s an example where we set operand 1 in the calculator after you add a calculator control , CalculatorControl1, to a standard VISUAL BASIC program; as you can see, this is just l ike sett ing the text in a textbox: .

Pr ivate Sub Command1_Cl ick ( )CalculatorControl1.Operand1=100

End Sub

To add the Operand1 and Operand2 propert ies to the Calculator ActiveX Project, open that Project in VISUAL BASIC, open the code windows, and select the Add Procedure box. Put the name of the first property, Operand1, in the Name box, and select the Option button labeled Property, then cl ick on OK. Doing so creates two procedures, a Let and Get procedure for the property. When Operand1 is set in code or by VISUAL BASIC, the Operand1 Let procedure is cal led; when other code or VISUAL BASIC wants to retr ieve the current value of Operand1, the Ooperand1 Get procedure is cal led. That means that we return the text in the two text boxes corresponding to the calculator’s operands in the Get procedures.

Publ ic Property Get Operand1 ( ) As VariantOperand1=Text1.Text

End Property

Publ ic Property Get Operand2( ) As VariantOperand2=Text2.Text

End Property

And we set the text in the operand text boxes from the values passed to us in the Let Procedures

Publ ic Property Let Operand1 ( ByVal vNewValue As Variant)Text1.Text=vNewValue

End Property

Publ ic Property Let Operand2 ( ByVal vNewValue As Variant )Text2.Text=vNewValue

End Property

Now, when you create a control of this type in another VISUAL BASIC program, you’ l l see that the new control has two new properties: Operand1 and Operand2. You can set those properties in the properties window at design t ime.

Private Sub Command1_Cl ick ( )CalculatorControl1.Operand1=100

End Sub

However, there is a problem. When you set the Operand1 and Operand2 propert ies at design t ime in a program that has a calculator control embedded in i t and then run the program, nothing appears in the operand text boxes. It turns out that we have to make the properties persistent i f we want to let the user set them at design t ime.

Making ActiveX Control Properties Persistent (PropertyBag Object)

There is a way of storing property sett ings in ActiveX controls that uses the PropertyBag Object. For example, i f you want the property sett ings the user makes in your control at design t ime to apply when the program runs, you must make the properties persistent. A persistent property is one whose value is stored and restored as needed.

Let’s see an example. Here, we’ l l make the Operand1 and Operand2 properties of the calculator ActiveX control we’ve developed in the previous few topics persistent. To do that, we first cal l the VISUAL BASIC PropertyChanged procedure when Operand1 or Operand2 is changed in i ts Let procedure. You pass the name of the property that’s been changed to PropertyChanged l ike this

Publ ic Property Let Operand1( ByVal vNewValue As Variant )Text1.Text=vNewValuePropertyChanged “Operand1”

End Property

Publ ic Property Let Operand2 ( ByVal vNewValue As Variant )Text2.Text=vNewValuePropertyChanged “Operand2”

End Property

When you cal l PropertyChanged, the control creates a WriteProperties event, and you can write the new sett ings of properties to the PropertyBag object , which stores them on disk. Here’s how you use WriteProperty.

Page 166: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 166

UserControl .WriteProperty ( Propertyname, Value [ , default ] )

For Example, to write the current sett ings of the calculator’s operands, we add this code to the WritePropert ies event handler.

Pr ivate Sub UserControl1_WriteProperties ( PropBag As PropertyBag )PropBag.WriteProperty “Operand1” , Text1.TextPropBag.WriteProperty “Operand2” , Text2.Text

End Sub

When the control needs to read its stored properties, i t creates a ReadProperties event, and in that event’s handler, we can use ReadProperty.

UserControl .ReadProperty ( propertyname [ , default ] )

Here’s how we use ReadProperty to read stored properties.

Private Sub UserControl_ReadProperties ( PropBag As PropertyBag )Text1.Text=PropBag.ReadProperty ( “Operand1” )Text2.Text=PropBag.ReadProperty ( “Operand2” )

End Sub

Now the Operand1 and Operand2 properties are persistent.Besides the WritePropert ies and ReadPropert ies events, user controls also have Init ial ize events that occur when the control is opened at design t ime and Terminate events that occur when you switch to runtime from design t ime. Here’s the order of events that occur when you switch from design t ime to runtime.

WriteProperties Terminate ReadProperties

And here’s the order of events that occur when you switch from runt ime to design t ime.

Init ial ize ReadProperties

Adding a Method to an ActiveX Control

You add a method to an ActiveX control in much the same way you add a property, with the Tool menu’s Add Procedure dialog box.

Let’s see an example. In this case, we’l l add a new method to the calculator ActiveX control that we’ve developed in the previous few topics: the Calculate method. When the control ’s Calculate method is cal led, we can add the values in the top two text boxes in the calculator and display the result in the bottom text box.

Open the calculator ActiveX project in VISUAL BASIC and open the code window as wel l . Next, select the Add Procedure item in Tools menu, open the add procedure dialog. Give this new method the name Calculate.

Select the entry labeled Sub to make our new method a Sub procedure, and make sure the entry labeled Publ ic in the Scope box is selected. Then cl ick on OK to close the Add Procedure dialog box. I f you have arguments you want passed to this method, just add them to the argument l ist between the parantheses as you would for any subroutine. In this case, we want to calculate the sum of the two operands now in Text1 and Text2 in this method, storing the sum in Text3, and we do that with this code

Publ ic Sub Calculate ( )Text3.Text=Str ( Val ( Text1.Text ) + Val ( Text2.Text ) )

End Sub

Now create the calculator control and embed it in another program as, say, CalculatorControl1. When you do, you can use the control ’s Calculate method l ike this

CalculateControl1.Calculate

For Example, Add a New button with the Caption Calculate to the Project and add the fo l lowing code to command button’s Cl ick event

Private Sub Command1_Cl ick ( )CalculatorControl1.Calculate

End Sub

When the User cl icks the Calculate button, we execute the CalculateControl ’s Calculate method.

Note:- Another way to set up methods in an Act iveX Control is to use the ActiveX Control Interface wizard in the Add-Ins menu.

Page 167: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 167

Adding an Event to an ActiveX Control

ActiveX Controls can support events, of course, and the custom ActiveX controls you design with VISUAL BASIC are no exception. You add events much l ike you add properties and methods, with Add Procedure item in the Tools menu. After you create a new event, i t ’s up to you to raise that event with the RaiseEvent method.

Let’s see an example. Here, we’ l l add an event named CalculatorCl ick to the calculator ActiveX control we’ve developed in the previous few topics. When the user cl icks the Calculator control , this event, CalculatorCl ick, wi l l occur.

To add this event to the Calculator Act iveX Control , open the calculator ActiveX project in VISUAL BASIC, open the code window, select Add Procedure in Tools menu, type the name of the event “CalculatorCl ick” in the name box, select the option button labeled Event to indicate that we want to create a new event, and cl ick OK. This creates the new event by declaring it in the Act iveX control ’s General sect ion.

If you want to add arguments to this event’s handler procedures, just l ist them in the parantheses as you would for any procedure.

You can make this event active using RaiseEvent method. In this case, that’s particularly easy- we’ l l just use the user control ’s Cl ick event. Add a Cl ick event handler to the calculator ActiveX control now.

Private Sub UserControl_Cl ick ( )RaiseEvent CalculatorCl ick

End Sub

Note : You can pass arguments to the events just as you would pass arguments to any procedure

RaiseEvent eventname ( [argumentl ist] )

Now when you embed the calculator control in a VISUAL BASIC program, you’ l l find that i t has a CalculatorCl ick that you can add text to

Private Sub CalculatorControl1_CalculatorCl ick ( )CalculatorControl1.Calculate

End Sub

Note : Another way to set up events in Act iveX control is to use the Act iveX control interface wizard in the Add-Ins menu.

Adding Design Time Property Pages

You can add property pages to your control with VISUAL BASIC property page wizard in the Add-Ins menu. I f that wizard does not appear in your Add-Ins menu, select the Add-In manager i tem in the Add Add-Ins menu and add the Property Page wizard. After you’ve added properties to an ActiveX Control , you can use the property page wizard to add property pages for those properties.

Let’s see an example. Here, we’l l add a set of property pages for our ActiveX calculator control that we’ve developed. Start the Property Page wizard by selecting that i tem in the Add-Ins menu now; a welcome screen wi l l appear. Cl ick the Next button unti l you get to the Select The Property Pages Screen. Here’s where you set up the property pages with the Add button and name them with the Rename button. In this case, the calculatorcontrol only has two properties, Operand1 and Operand2, and we’l l set up a separate property page for each. Cl ick next to go to the next screen, Add Properties from the l ist of al l the avai lable properties on the left to the property pages you’ve set up. Just cl ick the tab matching the property page you want to add a property to, select the property in the l ist box at left, and cl ick the r ight pointing arrow button to add that property to the property page. In this way you can organize which property appears on which page.

Final ly, c l ick Next to go to the Property Page wizards screen labeled Finished and cl ick the Finish Button. In this case, this creates two new property page documents, PropertyPage1.pag and PropertyPage2.pag, for your control , and adds them to your project. Save those files and rebui ld your control .

Now embed our ActiveX control in another program and open its property pages at design t ime.

ActiveX Documents ActiveX Documents are new to many programmers, but the idea is simple. Instead of restr ict ing yourself to a s ingle control in a Web page, now you can create the whole page. Act iveX documents can include as many controls as any other VISUAL BASIC program, and as we’l l see when we start creating Act iveX documents, the result is just l ike running a VISUAL BASIC program in your Web browser or other appl icat ion.

VISUAL BASIC ActiveX Documents are based on the VISUAL BASIC UserDocument object. When you create an ActiveX document, you save it with the extension .DOB. VISUAL

Page 168: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 168

BASIC uses that DOB file to create the EXE or DLL file that holds the actual code for the ActiveX document. In addit ion, VISUAL BASIC produces a specification file, with the extension .VBD, that describes the Act iveX document, and it ’s that file that you actual ly open in the host appl ication, such as the MicroSoft Internet Explorer. With ActiveX documents, you can let users save data using PropertyBag property that data is stored in the VBD file.

Creating an ActiveX Document

To creating a new ActiveX document, open the VISUAL BASIC New Project Dialog , select the ActiveX Document EXE entry, and cl ick on OK. This creates a new ActiveX document in VISUAL BASIC.

To get our start with ActiveX documents, just double-c l ick the document and add this code to the Init ial ize procedure that opens to draw a set of cr iss-crossing l ines and a black box in the center of the document.

Private Sub UserDocument_Init ial ize ( )Line ( 0 , 0 ) – ( ScaleWidth , ScaleHeight )Line ( 0 , ScaleHeight ) – ( ScaleWidth , 0 )Line ( ScaleWidth / 4 , ScaleHeight / 4 ) – ( 3 * ScaleWidth / 4 , _

3 * ScaleHeight / 4 ) , , BFEnd Sub

This is the procedure that’s run when the ActiveX Document is first opened. Because we’re drawing from the Init ial ize event handler, set the document’s AutoRedraw property to True.

Lets see our new Act iveX Document at work in a Web Browser. Select the Project1 Properties i tem in the Project menu, and cl ick the Debugging tab in the Project Properties dialog box that open. Make sure that the opt ion button labeled Start Component is selected and the box labeled Use Exist ing Browser is checked. Then close the dialog box by cl icking OK. Run the document with the start i tem in the Run menu.

Start ing the document loads the documents specification, a VBD file, into the browser, which runs the document’s EXE file or adds the document DLL file to i ts own process.

ActiveX Document DLLs Vs. EXEs

You can create both ActiveX document EXEs and DLLs. Here’s the difference, i f an ActiveX Document is written as an executable file ( EXE file ) , i t is an out-of process server and runs in i ts own process; i f i t has been implemented as a dynamic l ink l ibrary ( DLL ), i t is an in-process server and runs in the same process as the c l ient appl ication.

Although ActiveX Documents are usual ly bui lt as EXE projects, the benefit of DLLs is that appl ications that use in-process servers usual ly run faster than those that use out-of-process servers because the appl ication doesn’t have to cross process boundaries to use an object’s properties, methods, and events. In addit ion, the performance of an in-process component, or DLL file surpasses that of the same component compiled as an EXE. Also, mult iple programs accessing the same EXE can overwrite global data, but that doesn’t happen i f they each have their own in-process server.

In-Process Vs. Out-Of-Process Components

I f an Act iveX Component has been implemented as part of an executable file (EXE file), i t is an out-of-process server and runs in i ts own process. I f i t has been implemented as a dynamic l ink l ibrary (DLL file), i t is an in-process server and runs in the same process as the cl ient appl ication.

If your ActiveX component is an out-of-process server, i t is an EXE file, and can run stand alone. Appl ications that use in-process servers usual ly run faster then those that use out-of-process servers because the appl ication doesn’t have to cross process boundaries to use an object ’s properties, methods, and events.

There are a few reasons why you may want to create Act iveX document as an in-process component (DLL file). The performance of an in-process component surpasses that of the same component compiled as an EXE. In addit ion, mult iple programs accessing the same EXE can overwrite g lobal data; that doesn’t happen i f they each have their own in-process server.

With al l the different types of ActiveX components to choose from, how do you decide which type of component you want to create? Take a look attr ibute this l ist:

To bui ld an invis ible component that provides routines in code that you can cal l , bui ld a code component (ActiveX EXE or an Act iveX DLL)

To bui ld a component that can run in the same process with your appl icat ion, bui ld an ActiveX DLL.

To bui ld a component that can serve mult iple appl ications and can run on a remote computer, bui ld an ActiveX EXE.

To bui ld a vis ible component that can be dropped into an appl ication attr ibute design t ime, bui ld an ActiveX EXE

To bui ld a vis ible component that can take over an appl ication window attr ibute run t ime, bui ld an ActiveX Document

Page 169: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 169

Adding controls to an ActiveX Document

Using ActiveX documents, you can display ent ire forms in Web browsers. To see this at work, we’l l create a game example. This game wil l let user c l ick buttons to display alternate X’s and O’s. Working with mult iple controls in this way wi l l demonstrate how to display ent ire programs as Web Pages.

Create a new ActiveX Document ( EXE or DLL ) , and add nine command buttons to i t arranged in a 3 X 3 grid in c lassic t ic-tac-toe fashion. Give each button same name Command Clear each buttons Caption property, When VISUAL BASIC asks to Create Control Array, Cl ick YES.

To alternate X’s and O’s as the user cl icks buttons, we’ l l need a Boolean flag, which we’ l l cal l blnXFlag. I f this flag is True, the next capt ion to set wi l l be “X”; otherwise, “O”. Add the declarat ion of blnXFlag to the General Sect ion.

Dim blnXFlag As Boolean

We also init ial ize blnXFlag to True when the document first loads by adding this code to the Init ial ize event.

Private Sub UserDocument_Init ial ize ( ) BlnXFlag=True

End Sub

Now when the user cl icks a button, we alternate between sett ing the cl icked buttons captions to “X” and “O” this way.

Publ ic Command_Cl ick ( Index As Integer )I f blnXFlag Then

Command ( Index ) . Caption = “X”Else

Command ( Index ) . Caption = “O”End I f

blnXFlag = Not blnXFlagEnd Sub

At the end of the code, we toggle the state of blnXFlag for the next t ime the user cl icks a button.

Lets see our new Act iveX Document game at work. Select Project1 > Propert ies from Project menu, cl ick the Debugging tab in the Project Propert ies dialog box that opens. Make sure that the option button labeled Start Component is selected and the box labeled Use Exist ing Browser is checked. Then close the dialog box by cl icking OK. Run the game with the Start i tem in the Run menu.

As you can see, the ent ire program appears in Internet Explorer. The user can alternate button captions just by cl icking the buttons.

We’ l l save the document as activextictactoe.dob, and the project as activextictactoe.vbp. The default name for the document is UserDocument1, as you can see in the VISUAL BASIC Properties window; i f you want to use a different name for the document, set i t in the Properties window. We’l l change the document name to activextictactoedoc. When we create the VBD specification file for this document, then, that file wi l l be act ivextictactoedoc.vbd, and that’s the file to open in your Web browser.

Handling Constituent Control Events in an ActiveX Document

After you add controls to an Act iveX Document, how do you handle the events those controls create? That’s the beauty of i t al l - you handle such events just as you would in a Standard VISUAL BASIC EXE program, so designing an ActiveX Document is real ly just l ike designing a standard form in VISUAL BASIC.

Testing an ActiveX Document

To test an ActiveX Document and even Debug it whi le in design process, just fol low these steps.

Select the Projectname Properties i tem from Project Menu Click the Debugging tab in the Project > Properties Dialog Make sure that option button labeled Start Component is selected To use your exist ing browser, make sure the box labeled ‘Use Exist ing Browser’ is

checked. Close the dialog box by cl icking on OK Start the document with the start i tem in the Run menu.

When you fol low these steps, VISUAL BASIC creates a VBD file for your document and opens that file in your Web Browser.

Page 170: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 170

Creating ActiveX Documents that Run Outside VISUAL BASIC

ActiveX Documents need wither an EXE or DLL file and a VBD file. When you create an ActiveX Document, you save it with the extension .DOB. VISUAL BASIC uses DOB file to create the EXE or DLL file that holds the actual code for the ActiveX Document. To Create the EXE or DLL file, just select Make Projectname.EXE from Fi le Menu.

In addit ion VISUAL BASIC produces the specification file, with the extension .vbd, that describes the ActiveX Document, and it ’s that file that you actual ly open in the host appl ication, such as the Microsoft Internet Explorer. To open an ActiveX Document in Internet Explorer, you just open the VBD file directly.

Distributed Computing : ActiveX Documents and Integrated Browsers

I f you integrate a Web browser into a program, you can have that browser download ActiveX documents in a seamless way that makes those documents look l ike part of the program itself . In this way, users can download ActiveX documents fil led with current data into a program in a way that seems transparent to them.

Lets see an example, here, we’ l l add a Web browser to a program and use it to open the t ic tac toe Act iveX document. To create a program with a bui lt - in Web browser, use the VISUAL BASIC appl ication wizard. When the appl icat ion wizard asks you about internet connectiv ity, c l ick the opt ion button labeled Yes, and enter the URL of your document’s VBD file which can be on the internet in the startup URL box; here, we’l l use the disk location of your VBD file, which is

C:\VBBB\activextictactoedoc\act ivext ictactoedoc.vbd

Then cl ick Finish Button to create the program.

At design t ime, we can customize the program even more by changing the capt ion property pf the menu item that opens the game from “Web browser” to “Tic Tac Toe”, and edit ing the browser form, frmBrowser, by removing the combobox that shows the URL and al l the buttons. We can also stretch the Web browser control brwWebBrowser so it covers the whole frmBrowser form.

Customizing the browser form this way prevents i t f rom appearing as a Web browser at al l . Instead, i t wi l l look l ike a part of your program; the fact that i t comes from the Internet is entirely transparent to the user.

Running this program and selecting the Tic Tac Toe menu item opens that ActiveX Document in the program. The ActiveX Document looks just l ike any other part of the program, which is the idea behind distr ibuted computing.

Making ActiveX Document Properties Persistent ( PropertyBag Object )

Just as with Act iveX Controls, you can make the data in ActiveX Documents persistent, which means the data is stored by when you close the document and restored in the display when you open the document. To make the data in an Act iveX Document persistent, you use the PropertyChanged method l ike ActiveX controls, and use the ReadProperty and WriteProperty methods.

Lets see an example to make this c learer. Here, we’ l l store the data in the t ic-tac-toe ActiveX document game we’ve developed in the previous few topics. F irst, we noti fy the document that the game propert ies have changed by cal l ing PropertyChanged when the user cl icks a button.

Private Sub Command_Cl ick ( Index As Integer )I f blnXFlag Then

Command ( Index ) . Caption = “X”Else

Command ( Index ) . Caption = “O”End I f

blnXFlag= Not blnXFlagPropertyChanged

End Sub

Next, we add code to the WriteProperties event handler to write the captions of the buttons to the PropertyBag object using that object’s WriteProperty method.

Private Sub UserDocument_WriteProperties ( PropBag As PropertyBag )Dim intLoopIndex As Integer

For intLoopIndex = 0 to 8PropBag.WriteProperty “Command ( “ & Str ( intLoopIndex ) & “ ) “, _

Command( intLoopIndex ) . CaptionNext

End Sub

In addit ion, we read the property sett ings back in when needed in the ReadPropert ies event handler.

Page 171: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 171

Private Sub UserDocument_ReadProperties ( PropBag As PropertyBag )Dim intLoopIndex As Integer

For intLoopIndex= 0 to 8Command ( intLoopIndex ) . Capt ion = PropBag.ReadProperty _

( “Command ( “ & Str ( intLoopIndex ) & “ ) ”

NextEnd Sub

With this new code, the user can make changes to the ActiveX Document when it ’s open in the Web browser and save those changes in the document.

Code Components

Code Components were formerly cal led OLE automation servers. These objects lets you use their code in other programs. For example, you might have a calculation routine that you expose in a code component; doing so makes that routine avai lable to other programs. Code components can support properties and methods.

Creating Code Components

A Code Component-formerly cal led OLE automation servers- as a l ibrary of objects, ready to be used by other appl ications cal led cl ient appl ications. For example, you might have a terr ific routine to sort records that you want to use in a dozen different programs. You can put that rout ine in a code component, register i t with Windows, and then you’re free to use the routine in that code component in other programs- just as with an ActiveX control , the other programs can cal l the code components methods and properties.

A Code component is l ike an ActiveX control or document that doesn’t create a visual display in a host appl icat ion. Code components provide access to methods and properties through code, not a direct graphical user interface.

In fact , code components are the third part of the standard Act iveX object set that VISUAL BASIC supports: Act iveX controls, Act iveX documents, and code components. You bui ld code components as ActiveX EXEs or Act iveX DLLs, much as you do with ActiveX controls or documents.

Code Components: Classes and Objects

When you create a code component, you add code in class module(s), and when you register the code component with Windows, you make the c lass(es) avai lable to c l ient appl ications. Those appl icat ions, in turn, can add a reference to your code component and create an object of the c lass they want to use with the New, CreateObject, or other VISUAL BASIC instruct ion. When the c l ient appl ication has an object corresponding to one of your c lasses, i t can use that c lass’s propert ies and methods.

That is how it works- it ’s al l about reusing your code. You get an object corresponding to a class in a code component l ike this, where we’re creating an object, objCalendar, of the class CalendarClass from the hypothetical code component named PlannerCodeComponent.

Dim objCalendar As ObjectSet objCalendar=CreateObject(“PlannerCodeComponent.CalendarClass”)

Then you can use that object’s properties and methods to give you access to the code in the class, l ike this

Dim objCalendar As ObjectSet objCalendar=CreateObject(“PlannerCodeComponent.CalendarClass”)

ObjCalendar.Days=365 ‘ use a propertyIntWorkDays=objCalendar.CalculateWorkDays ‘ use a method

If you have created your code component as ActiveX EXE, that code component is an out-of-process server and runs separately from the cl ient appl ication; i f you have created your code component as ActiveX DLL, that code component is an in-process server, which means it ’ l l run as part of the cl ient appl ication’s process.

There’s even a way to use code components without creating an object. To make it easy to create code components that can be used with desktop tools l ike the Microsoft Office Suite, VISUAL BASIC al lows you to label objects in a code component as global, which means they are part of a global object . In practice, this means that you don’t have to create an object to use the methods and properties of this code component- you just add a reference to the code component in the cl ient appl ication, and you can use the component’s properties and methods as though they were part of the c l ient appl ication.

A cl ient appl ication and an in-process component share the same memory space, so cal ls to the methods of an in-process code component can use the cl ient’s stack to pass arguments. That’s not possible for an out-of-process component; there, method arguments must be moved across the memory boundary between the two processes, which is cal led marshal ing.

Page 172: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 172

Code Components and Threads

When you start working with another appl icat ion, as code components do, you share threads of execution with that appl ication in a joint process. As a default, the Microsoft Component Object Model (COM) deals with this s ituation by serial iz ing thread operations. That is, the operations are queued and processed, one attr ibute t ime, unti l they al l have been completed.

That process is safe, and you don’t have to think about i t except for performance issues. In a mult ithreading operating environment, seria l ization protects s ingle-threaded objects from overlapping cl ient operations. However, serial iz ing single-threaded components also means that operat ions can be blocked, and can stay blocked for some t ime, which can be frustrating.

VISUAL BASIC has two ways to avoid blocked cal ls. Mult ithreading and SingleUse objects.

Multithreading Code components

You make in-process and out-of-process code components mult ithreaded by changing their threading model. VISUAL BASIC uses its apartment-model threading to ensure thread safety when you’re working with mult iple threads. In apartment-model threading, each thread is l ike an apartment-al l objects created on the thread work in an apartment, and they are not ‘aware’ of the objects in other apartments. This threading model a lso el iminates conflicts when accessing global data from mult iple threads by giving each apartment i ts own copy of that global data. You can use apartment-model threading without having to el iminate visual elements such as forms and controls, because al l such VISUAL BASIC objects are thread-safe.

You can specify the apartment threading model instead of s ingle threaded model for in-process code components to make them multithreaded. To make out-of-process code components mult ithreaded, you have two options: thread pool ing and the thread-per-object model. With thread pool ing, you can specify how many threads you want avai lable for your code components, and those threads are used in a round-robin way that is , the first object is created on the first thread in the pool and thread al location keeps going thread by thread, start ing over with the first thread when the others in the pool are used. I f you specify the thread-per-object model, each new object is created with its own thread.

SingleUse Code components

You can also handle serial ization conflicts by creating SingleUse code components, in which every new object of your code component c lass creates a new instance of the component. You do this by sett ing the class’s Instancing property. The Instancing property indicates how you want your c lass to interact with cl ient appl ications, i f at al l . Here are the possible values of that property:

Private Other appl ications aren’t al lowed access to type l ibrary information about the c lass and cannot create instances of i t . Pr ivate objects are only for use within your component.

Publ icNotCreatable other appl ications can use objects of this c lass only i f your component creates the objects first. Other appl ications cannot use the CreateObject function or the New operator to create objects from the class.

Mult iUse other appl ications are al lowed to create objects from the c lass. One instance of your component can provide any number of objects created in this fashion. An out-of-process component can supply mult ip le objects to mult iple cl ients; an in-process component can supply mult ip le objects to the c l ient and to any other components in i ts process.

GlobalMult iUse similar to Mult iUse, with one addit ion: properties and methods of the c lass can be invoked as i f they were simply global funct ions. It ’s not necessary to expl ic it ly create an instance of the c lass first, because one wi l l automatical ly be created.

SingleUse other appl ications are al lowed to create objects from the c lass, but every object of this class that a cl ient creates starts a new instance of your component. Not al lowed in ActiveX DLL projects.

GlobalSingleUse similar to SingleUse, except that propert ies and methods of the class can be invoked as i f they were simply g lobal functions. Not a l lowed in ActiveX DLL projects.

Overal l , then, the reason you use code components is to make it easy to reuse your code in other appl ications.

Page 173: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 173

Chapter 32

Integrating the Internet into VISUAL BASIC

Creating A Web Browser

I f you have Microsoft Internet Explorer instal led, you can bui ld Web browsers using VISUAL BASIC. Microsoft has packaged the Internet Explorer in a control , the WebBrowser control , and we’l l be able to use that control to create a Web Browser that supports such browser functional ity as Back, Forward, Home, Stop, and Refresh buttons. We’l l also let the user specify what URL to navigate to with a combo box- as wel l as keeping track of recently vis ited URLs in that combo box. Bui lding a Web Browser can be a worthwhile project in i tself, but another popular use of the WebBrowser control is to add a WebBrowser to your exist ing program for added power. In fact , you can use the WebBrowser control to open ActiveX documents in a way that makes them look l ike a seamless part of the program-even though that document may have come from the Internet.

Create a new standard Exe project Select Project > Components, Cl ick Controls tab Select Microsoft Internet Controls and Microsoft Windows Common Controls, and

Cl ick OK. Add a WebBrowser Control and a Toolbar to the form, stretching the WebBrowser

control to fil l the space under toolbar. Add Five Buttons to the toolbar by r ight c l ick and choose propert ies Give the buttons the same captions and key properties Back, Next, Home, Stop,

and Refresh Add a ComboBox to the End of Toolbar by choosing it from the toolbox and draw it

on toolbar.

Now, that you setup the controls need in Web Browser. To navigate you use the WebBrowser’s Navigate method. For Example, when our web browser first loads, we can navigate to a web page as below

Private Sub Form_Load( )

WebBrowser1.Navigate “www.hotmail .com”

End Sub

Add the present URL to the combo box using Add method

Private Sub Form_Load( )

WebBrowser1.Navigate “www.hotmail .com”Combo1.Text=”www.hotmail .com”Combo1.AddItem Combo1.Text

End Sub

Users can select the URLs from the combo box’s drop down l ist. Write the code in Cl ick event of Combo Box

Private Combo1_Cl ick( )

WebBrowser1.Navigate Combo1.Text

End Sub

In addit ion, users can type a new URL into the combo box and press enter. So write the fo l lowing code in KeyPress event of Combo Box

Private Combo1_KeyPress( KeyAsci i As Integer)

If KeyAsci i=13 thenCombo1_Cl ick

End I f

End Sub

Final ly, when the Downloading process is complete, the WebBrowser control fires a DownLoadComplete event, and we can display the present URL in the browser’s t i t le bar, just as any commercial browser might. To document that, we get the browser’s present URL from its LocationName property. Also we can add that URL to the top of the combo box' ’ l ist.

Pr ivate Sub WebBrowser1_DownLoadComplete( )

Page 174: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 174

Me.Caption=WebBrowser1.LocationNameCombo1.AddItem WebBrowser1.LocationURL, 0

End Sub

Adding Back and Forward Buttons to a Web Browser

To enable Back and Forward buttons, use the browser’s GoBack and GoForward methods.

Private Sub Toolbar1_ButtonCl ick( ByVal Button As Button)Select Case Button.Key

Case “Back”WebBrowser1.GoBack

Case “Forward”WebBrowser1.GoForward

End SelectEnd Sub

Adding Refresh, Home, and Stop buttons to a Web Browser

We can implement the buttons Refresh, Home and stop using Web browser’s Refresh, GoHome, and Stop methods.

Private Sub Toolbar1_ButtonCl ick( ByVal Button As Button)Select Case Button.Key

Case “Back”WebBrowser1.GoBack

Case “Forward”WebBrowser1.GoForward

Case “Refresh”WebBrowser1.Refresh

Case “Home”WebBrowser1.GoHome

Case “Stop”WebBrowser1.StopMe.Caption=WebBrowser1.LocationName

End SelectEnd Sub

Creating Dynamic HTML (DHTML) page

DHTML is the new, web page standard. The Microsoft standard for DHTML makes al l the tags in a Web page act ive elements in the sense that they have properties you can change at run t ime, as wel l as events l ike Cl ick. The DirectAnimation and DirectShow Internet Explorer packages are part of Microsoft DHTML as wel l .

VISUAL BASIC can write DHTML- in fact, you can use VISUAL BASIC as an HTML editor, adding text, images, hyperl inks, and tables. You can add ActiveX controls directly to your web pages when designing them in the DHTML designer.

Creating DHTML pages

To create a DHTML page, Choose Fi le New Project , Select Dynamic HTML Appl ication item in the dialog and cl ick OK. This opens DHTML page designer.

You add the elements you want in your page to the r ight window in the Page Designer, and it gives you an idea of how the page wi l l look in the browser. The window on the left in the Page Designer shows the logical structure of the page by indicating which HTML elements are contained in other HTML elements. Using the Page Designer, then, you can get an idea of both how your page wi l l look and how it ’s organized in HTML.

Note that when you can use VISUAL BASIC in the DHTML pages designed with VISUAL BASIC. It is possible because what you’re real ly creating is an ActiveX DLL project that wi l l be loaded into the Internet Explorer when you open the Web Page. The DLL runs in the Internet Explorer’s process. To make the needed DLL file, just select the Make Projectname.DLL item in Fi le menu.

You may be want to create an HTML Web Page, without any DLL files at a l l , and you can do that too. Usual ly, the HTML page is stored in VISUAL BASIC project. To store it in a separate HTM file, cl ick the DHTML Page Designer Properties icon at the upper left in DHTML Page Designer, select the Save HTML in an external file option, and give an HTM filename to save your web page as. To test the web page, select the DHTML project Properties i tem in the project menu, c l icking the Debugging tab in the Properties pages that open. make sure the Start Component opt ion button is c l icked and the start component is set to DHTMLpage1, then cl ick OK. Now select the Start i tem in the Run menu to open the Web Page.

Adding Text to DHTML pages

To add text in pages, just c l ick in the r ight window in the DHTML page designer where you want text and type the text you want. Adding the text we’ve placed in our Web Page adds this HTML to the Web page itself-note the Page Designer uses the <P> paragraph HTML tag for each paragraph of text.

Page 175: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 175

You can format the text by selecting the text font, s ize, and style with controls at the top of the page designer. You can also specify i ts al ignment-r ight, center, or left-with buttons in the page designer toolbar.

Adding Images to DHTML Pages

To add an image to a DHTML page in the VISUAL BASIC DHTML Page Designer, you cl ick the image tool . Doing so adds an empty image to the page; move that image to the posit ion you want and size it appropriately.

To add an image to this DHTML control , set i ts src property. In this case, we set the src property to an image on the disk for example file:// /c: /windows/cloud.bmp, also you can use a URL here.

Adding HTML controls to DHTML pages

Using VISUAL BASIC DHTML Page designer, you can add the standard HTML controls to a Web page : buttons, Submit buttons, Reset Buttons, text fields, text areas, password fields, opt ion buttons, checkboxes, select controls, file upload controls, hidden fields, and l ists. Adding these controls to your web page is just l ike adding them to a standard VISUAL BASIC project. You just use the control ’s tool in the Page Designer’s toolbox in the same way you’d use a tool in the VISUAL BASIC toolbox.

Adding ActiveX Controls to DHTML Pages

You can add ActiveX controls to DHTML pages just as you can to standard VISUAL BASIC projects- just use the Project > Components menu item to open the Components Dialog and select the ActiveX control you want to add. Then just add that control to the Web page as you would in any standard VISUAL BASIC project .

Adding Tables to DHTML Pages

One popular HTML element is the table. Tables can present data in tabular form, but many HTML programmers use them for much more. They use tables to format the elements in a Web Page, placing those elements at locations they want by inserting them into a table. For example you can add sidebars and format image placement with hidden tables. Although the Dynamic HTML posit ion attr ibute helps you place HTML elements where you want them, that attr ibute is not yet supported by al l browsers. To add a table to a DHTML page, you use the Table Operation drop-down box. To insert a table, use the Insert Table Entry in that drop-down box. When you document, the Page Designer adds a 2 X 2 table to the page. To add a row, select the Insert Row entry in the Table Operation drop-down box; to add a column, select the Insert Column Entry.

Adding Hyperlinks to DHTML pages

To add hyperl ink to a DHTML page, you use the Hyperl ink tool in the DHTML page designers toolbox. When you double c l ick the hyperl ink tool , a hyperl ink object is added to the Web Page with the caption Hyperl ink1. Move that hyperl ink to the location you want in the Web page, change its caption to the text you want s imply by changing the text in the hyperl ink object directly. To set the target URL, r ight cl ick the hyperl ink and select the Properties i tem in the menu that opens. Next, place the target URL in the box labeled l ink.

That’s i t -to run the Web Page, select the DHTML project properties i tem in the Project menu, cl ick the debugging tab in the Propert ies pages that open. Make sure that Start Component option button is cl icked and the start component is set to DHTMLPage1, then cl ick OK. Now select the start i tem in the Run menu to open the Web page.

Working With Email

VISUAL BASIC includes support for working with email as wel l . That support is based on the Microsoft Exchange uti l i ty that’s instal led with Windows. We’l l use the ActiveX MAPI controls (Messaging Appl ications Programming Interface) to connect VISUAL BASIC to Microsoft Exchange to handle Email . To connect to the email system, you create a new MAPI session using the MAPISession control . When the session is created, you use the MAPIMessages control to work with individual messages. Note that these controls are interfaces to the Microsoft Exchange package, which means that we’ l l be using that package to send and receive email .

Using MAPI controls to support Email

I f you want to run a program that uses the MAPI controls, make sure that you have the 32-bit MAPI DLLs instal led properly or you may not be able to perform simple MAPI functions such as S ignOn. For example, on Windows 95, you must instal l Mai l during the operating system setup or instal l i t separately from the control panel to correctly use MAPI functions or MAPI custom controls from VISUAL BASIC. The VISUAL BASIC email support is based on the Microsoft Exchange uti l i ty that’s instal led with Windows. I f you want to use the MAPI controls, make sure your desktop inbox is configured to send and receive email .

There are two MAPI controls, the MAPIsession control and the MAPIMessages control . To add these controls to a program, fo l low these steps.

Select the Project > Components menu item.

Page 176: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 176

Click the controls tab in the Components dia log box that opens Select the entry labeled Microsoft MAPI controls, and Cl ick on OK to close the

components d ialog box. Step 3 adds both the MAPISession control and the MAPIMessages control to the

VISUAL BASIC toolbox. You’ l l need to add one of each of those controls to your program to use email .

You use the MAPISession control to open a new MAPI session, which is the first step to sending or receiving email , and the MAPIMessages control lets you compose, send, and examine downloaded messages.

The MAPIMessages control is the primary control you use in your code. To work with the MAPIMessages control , you keep track of two buffers, the read buffer and the compose buffer.

The read buffer is made up of a set of messages read from a user’s Inbox. The MsgIndex property is used to address indiv idual messages within this set, start ing with a value of 0 for the first message and incrementing by one for each message. You get the actual e-mail ’s text from the control ’s MsgNoteText property.

Messages can be created or edited in the compose buffer. The compose buffer is automatical ly set as the act ive buffer when the MsgIndex property is set to –1.

The MAPIMessages control ’s message set is bui lt with the Fetch method. This set includes al l messages of type specified by the FetchMsgType property and is sorted as indicated by the FetchSorted property. Messages in the read buffer can’t be altered by the user but can be copied to the compose buffer for alteration using the Copy method.

MAPIMessages control email methods

Function Method

Get Email from Inbox FetchSend Email with Compose Box SendSend email SendSave a message SaveCopy a message for reply CopyCompose Email ComposeReply to a message ReplyReply to al l messages ReplyAl lForward a Message ForwardDelete a Message DeleteShow Address book ShowShow message detai ls ShowResolve recipient name ResolveNameDelete recipient DeleteDelete attachment Delete

MAPIMessages control properties

Property Description

Action Obsolete, performs actions now performed by methods.AddressCaption Sets caption of the address bookAddressEditFieldCount sets which address book edit controls to d isplayAddressLabel Sets appearance of “To” edit control in address bookAddressModifiable Sets whether address book can be modified by User.AttachmentCount Gets total number of attachments to current sett ingsAttachmentIndex Sets currently indexed attachmentAttachmentName Sets name of the currently indexed attachmentAttachmentPathName Sets ful l pathname of the currently indexed attachmentAttachmentPosit ion Sets posit ion of indexed attachment in the message boxAttachmentType Sets type of currently indexed attachmentFetchSorted Sets message order when creating message setMsgConversationID Sets the conversat ion thread ident ification valueMsgCount Gets the total no. of messages in message setMsgDateReceived Gets date on which current indexed message was receivedMsgID Gets str ing identifier of current messageMsgIndex Sets Index number of current messageMsgNoteText Text of current messageMsgOrigAddress Gets email address of or iginator of current messageMsgOrigDisplayName Gets originator’s name for current messageMsgRead True or False depending on whether message has been readMsgReceiptRequested Indicates i f return receipt is requested for messageMsgSent Indicates i f message has been sent to mail server.MsgSubject Message’s SubjectMsgType Sets type of current message

Page 177: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 177

Sending Email From VISUAL BASIC

Let’s use an example. Create a new standard EXE project , and add the MAPISession and MAPIMessages controls MAPISession1 and MAPIMessages1. Next add two buttons Command1 and Command2, with capt ion “Send mail” and “Read mail”. Add a text box, Text1, to the form, sett ing its Mult iLine property to True and its Scrol lBars property to Both (3).When user cl icks “send mail” button, let them document so using the MAPIMessages control ’s Compose and Send methods. Our first task, however, is to start a new MAPI session, and we do that with the MAPISession control ’s SignOn method, after indicating that we don’t want to download email by sett ing its DownLoadMail property to False.

After s igning on to the Microsoft Exchange email system, we set the MAPIMessages control ’s SessionID to the MAPISession control ’s SessionID property to init ial ize MAPIMessages1.

To Compose a new email message, we have to set the MAPIMessages1 control ’s MsgIndex property –1 and cal l i ts Compose method.

Users can enter the email text and address they want to use in that d ialog and cl ick Send button to send the mail .

When the user is done composing the email , we send it with the MAPIMessages1 control ’s Send method and sign off the MAPI session using the MAPISession1 control ’s SignOff method.

Private Sub Command1_Cl ick( )

MAPISession1.DownLoadmail=FalseMAPISession1.SignOn

MAPIMessages1.SessionID=MAPISession1.SessionIDMAPIMessages1.MsgIndex=-1MAPIMessages1.Compose

MAPIMessages1.Send TrueMAPISession1.SignOff

End Sub

That’s i t we’ve sent out mail .

Reading Email in VISUAL BASIC

To read mail you set the MAPISession control ’s DownLoadMail property to True. Let’s use an example, we’l l download any wait ing email into the user’s Inbox and then display the first message in a text box. We’ l l use the program we started in the previous session and add code to the “read mail” button. First, we set the MAPISession control ’s DownLoadMail property to True, then we use that control ’s SignOn method to start the MAPI session and download any wait ing email into the Inbox.

We use MAPIMessages control ’s Fetch method to create a message set. To document that, we first set the MAPIMessages control ’s SessionID property to the MAPISession control ’s SessionID property and then use Fetch.

Next, we display the text of the first email message now in the Inbox by sett ing the MAPIMessages control ’s MsgIndex to 0 and using the MsgNoteText property. Final ly we sign off the MAPI session.

Private Sub Command2_Cl ick ( )

MAPISession1.DownLoadMail=TrueMAPISession1.SignOn

MAPIMessages1.SessionID=MAPISession1.SessionIDMAPIMessages1.Fetch

MAPIMessages1.MsgIndex=0Text1.Text=MAPIMessages1.MsgNoteText

MAPISession1.SignOff

End Sub

Using FTP

FTP (Fi le Transfer Protocol) is a very popular Internet protocol for as i ts name implies, transferr ing files. VISUAL BASIC has good support for FTP work, and that support is contained in the VISUAL BASIC Internet transfer control . That control has two approaches to working with FTP. You can use the OpenURL method to easi ly download a file from an

Page 178: VISUAL BASIC - ::ICES::INDIAN COMPUTER … Notes.doc · Web viewIf the Keyword Step follows the word Circle, then X and Y coordinates are relative to the values of CurrentX and CurrentY

NetScape COMPUTER ACADEMY 178

FTP site. In addit ion, you can execute standard FTP commands with the control ’s Execute method. Using Execute, you can make use of the standard FTP commands l ike CD, GET, CLOSE, QUIT, SEND and so on.

Using HTTP

HTTP (Hyper Text Transfer Protocol) is the protocol on which the World Wide Web is based. As most programmers know, this is the protocol used for Web pages on Internet. When you download a file using the Internet transfer control ’s OpenURL method, you get access to the file’s HTML directly, which is important i f you want to interrupt that HTML in a way different from how the Internet Explorer would. You can also use that control ’s Execute method to execute HTTP commands directly. Besides using Internet transfer control ’s OpenURL method, you can also use the Execute method to execute such common HTTP commands l ike GET, POST and PUT.

Using the Internet Transfer Control for FTP and HTTP operations

You use the Microsoft Internet Transfer Control to handle FTP and HTTP operation in VISUAL BASIC. Using the HTTP protocol, you can connect to world wide web servers to retreive HTML documents. With FTP protocol, you can log on to FTP servers to download and upload files.

The UseName and Password properties that al low you to log on to private servers that require authentication. Otherwise, you can connect to publ ic FTP servers and download files. The common FTP commands, such as CD and GET, are supported through Execute method. You can keep track of the Internet transfer control ’s operations with the Sti l lExecuting property. I f this property is true, the control is working on a transfer and wi l l not respond to others actions.

The internet transfer control performs asynchronous Internet transfers, so besides the Sti l lExecuting property, Microsoft has given the control a StateChanged event. In this event’s handler procedure, you are kept up-to-date on what’s going on with Internet transfer protocol.

Pr ivate Sub object_StateChanged(ByVal State As Integer)

End Sub

The State argument can take these values

icNone-0; no state to report icHostResolvingHost-1; the control is looking up the IP address of the specified

host computer. icHostResolved-2; the control successful ly found the IP address of the specified

host computer. icConnecting-3; the control is connecting to the host computer icConnected-4; the control successful ly connected to the host computer icRequesting-5; the control is sending a request to the host computer icRequestSent-6; the control successful ly sent the request icReceivingResponse-7; the control is receiving a response from the host computer icResponseReceived-8; the control successful ly received a response from the host

computer icDisconnecting-9; the control is disconnecting from the host computer icDisconnected-10; the control successful ly disconnected from the host computer icError-11; an error occurred in communicating with the host computer icResponseCompleted-12; the request has completed and al l data has been

received

note that when a request is finished, the State argument in the StateChanged event wi l l be set to icResponseCompleted, and it ’s safe to execute another command with the Internet transfer protocol.

To add an Internet transfer control to a program, fol low these steps:

1. select Project> Components2. Cl ick the controls tab in components dialog box3. Select the entry labeled Microsoft Internet Transfer Protocol4. Cl ick on OK to close the Components dia log to add the Microsoft Internet Transfer Control tool to the Toolbox5. Double c l ick Microsoft Internet Transfer Control tool to the toolbox and add that control to your form. This control is invis ib le at runt ime, so its size and locat ion are not important.6. Add the code you want to use with the control to your program

When you start an FTP or HTTP operation with Internet transfer control , the control wi l l connect to the Internet i f the computer is not a lready connected.