0% found this document useful (0 votes)
36 views60 pages

VB One Two

The document outlines the curriculum for the Visual Basic course at NANDHA Arts and Science College, covering essential topics such as the programming environment, menus, data access objects, object linking and embedding, and various controls. Each unit consists of detailed content and practical applications, emphasizing hands-on development using Visual Basic 6.0. Additionally, it includes references to textbooks and resources for further study.

Uploaded by

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

VB One Two

The document outlines the curriculum for the Visual Basic course at NANDHA Arts and Science College, covering essential topics such as the programming environment, menus, data access objects, object linking and embedding, and various controls. Each unit consists of detailed content and practical applications, emphasizing hands-on development using Visual Basic 6.0. Additionally, it includes references to textbooks and resources for further study.

Uploaded by

jegan20052006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NANDHA ARTS AND SCIENCE COLLEGE,ERODE - 52

DEPARTMENT OF INFORMATION TECHNOLOGY

III YEAR 2025-2026

CORE 9:VISUAL BASIC


SUB CODE:53B

REGISTER NO :

NAME :

CLASS :

1
NASC-B.SC(INFORMATION TECHNOLOGY)
Unit:1 INTRODUCTION TO VB 15 hours
Getting Started with VB6, Programming Environment, working with Forms, Developing
an application, Variables, Data types and Modules, procedures and control structures,
arrays. Working with Controls: Creating and using controls, working with control
arrays.
Unit:2 MENUS IN VB 15 hours
Menus, Mouse events and Dialog boxes: Mouse events, Dialog boxes, MDI and Flex grid:
MDI, Using the Flex grid control.

Unit:3 ODBC AND DATA ACCESS OBJECTS 15 hours


ODBC and Data Access Objects: Data Access Options, ODBC, Remote data objects,
ActiveX EXE and ActiveX DLL: Introduction, Creating an ActiveX EXE Component,
Creating ActiveX DLL Component.

Unit:4 OBJECT LINKING AND EMBEDDING 15 hours


Object Linking and Embedding: OLE fundamentals, Using OLE Container Control,
Using OLE Automation objects, OLE Drag and Drop, File and File System Control: File
System Controls, Accessing Files.

Unit:5 CONTROLS IN VB 12 hours


Additional controls in VB: sstab control, setting properties at runtime, adding controls
to tab, list control, tabstrip control, MS Flexgrid control, Why ADO, Establishing a
reference, Crystal and data reports.

Text Book(s)
1 Visual Basic 6.0 Programming, Content Development Group, TMH, 8th
reprint, 2007. (Unit I to Unit IV)
2 Programming with Visual Basic 6.0, Mohammed Azam, Vikas Publishing
House, Fourth Reprint, 2006. (Unit V)
3

Reference Books
1 Gray Cornell (2003), ”Visual Basic 6 from ground up” TMH, New Delhi,
1st Edition,
Deitel and Deitel, T.R.Nieto (1998), “Visual Basic 6 - How to Program”,
2
Pearson Education. First Edition.

2
NASC-B.SC(INFORMATION TECHNOLOGY)
Unit:1 INTRODUCTION TO VB 15 hours

Getting Started with VB6, #1 Programming Environment, #2


working with Forms, #3 Developing an application, #4 Variables, #5
Data types ,#6 Modules, #7 procedures ,#8 control structures, #9
arrays. Working with Controls: Creating and using controls,
working with control arrays.

Getting Started with the VB6 IDE

Once you install VB6, you'll be greeted with the Integrated Development
Environment (IDE), as shown below. This is where you design forms, write
code, and run your application.

3
NASC-B.SC(INFORMATION TECHNOLOGY)
#1 Visual Basic Programming Environment:

1. IDE (Integrated Development Environment):

o The main workspace where development happens. Visual Studio


is the most commonly used IDE for Visual Basic.

2. Code Editor:

o Where you write the Visual Basic code.

o Features include syntax highlighting, IntelliSense (code


suggestions), and auto-completion.

3. Toolbox:

o Contains a list of controls (like buttons, labels, textboxes) that


you can drag and drop onto a form to design your user interface
(UI).

o These are known as Windows Forms Controls for desktop


apps.

4
NASC-B.SC(INFORMATION TECHNOLOGY)
4. Form Designer:

o A visual design surface for creating the UI.

o Lets you arrange controls like buttons, textboxes, and labels on


a form visually.

5. Solution Explorer:

o Displays the structure of your project (forms, modules,


references, resources).

o Helps manage multiple files and components of the project.

6. Properties Window:

o Used to view and modify the properties of selected objects (like


changing the text of a label or setting the color of a button).

o The property window is docked under the project explorer


window.

5
NASC-B.SC(INFORMATION TECHNOLOGY)
7. Error List / Output Window:

o Shows compilation errors, warnings, and runtime messages.

o Helps in debugging and troubleshooting.

8. Debugger:

o Allows you to run your program step-by-step to find and fix


bugs.

o Includes breakpoints, watches, and variable inspection tools.

9. Project & Solution:

o A project is a collection of files that make up an application.

o A solution can contain one or more related projects.

10.Compiler:

o Translates your VB code into executable machine code.

o Handled automatically by the IDE when you build or run the


program.

Example Development Flow in VB:

1. Open Visual Studio and create a new Windows Forms App (.NET
Framework).

2. Use the Form Designer to design your interface.

3. Double-click a button to write event-handling code in the Code


Editor.

6
NASC-B.SC(INFORMATION TECHNOLOGY)
4. Run the program using the Start button.

5. Debug any errors using the Output Window and Debugger.

#2 DEVELOPING AN APPLICATION:

Step-by-Step: Developing an Application in Visual Basic

1. Set Up the Environment

• Install Visual basic 6.0 (Community Edition is free).

• During installation, select the “.NET desktop development”


workload.

2. Create a New Project

1. Open Visual basic 6.0.

2. Click “Create a new project”.

3. Select “standard exe (.NET Framework)” and click Next.

4. Name your project (e.g., MyFirstVBApp), choose the location, and click
Create.

3. Design the User Interface (UI)

• You’ll see a blank form (like a blank window).

• Open the Toolbox (View > Toolbox).

• Drag and drop controls (buttons, labels, textboxes, etc.) onto the form.

Example Layout:

• Label: “Enter your name:”

• TextBox: For user input

• Button: “Greet Me”

• Label: For displaying greeting message

7
NASC-B.SC(INFORMATION TECHNOLOGY)
4. Write the Code (Event Handling)

Double-click the button to open the code editor. Then write your Visual
Basic code inside the button’s click event:

Private Sub btnGreet_Click(sender As Object, e As EventArgs) Handles


btnGreet.Click

Dim userName As String

userName = txtName.Text

lblGreeting.Text = "Hello, " & userName & "!"

End Sub

In this code:

• txtName is the name of the textbox.

• lblGreeting is the label that displays the greeting.

5. Run the Application

• Click the Start button (green play icon) or press F5.

• The form will launch as a standalone window.

8
NASC-B.SC(INFORMATION TECHNOLOGY)
• Test the button to see the greeting based on input.

6. Debug and Test

• If there are any errors, Visual Studio will highlight them.

• Use the Output Window and Error List to debug.

• Set breakpoints and use the Debugger if needed.

7. Build the Application

• When you're done, go to Build > Build Solution to compile the app.

• To create a distributable version: go to Build > Publish and follow the


wizard to package the application.

Step Description

1 Install Visual Studio and create a project

2 Design the user interface using drag-and-drop

3 Write event-driven VB code for logic

4 Run and test the application

9
NASC-B.SC(INFORMATION TECHNOLOGY)
Step Description

5 Debug and handle errors

6 Build and publish your final application

#3 WORKING WITH FORMS

1. Creating a Form in VB6

In VB6, forms are the main building blocks for creating the user interface
(UI) of your application. They are essentially windows that users interact
with. When you create a new project in VB6, the default form (Form1) is
automatically created for you.

If you want to add more forms to your project:

• Go to the Project menu at the top.

• Select Add Form. This will allow you to add additional forms to your
project (e.g., Form2, Form3, etc.).

Each form can be treated as a standalone UI or as a child window within a


larger Multiple Document Interface (MDI), which allows for managing
multiple forms within the same application window.

2. Form Properties

Forms in VB6 come with various properties that you can configure to
customize the appearance and behavior of the form. These properties are
accessed through the Properties window.

Here’s an explanation of some common form properties:

• Name:

o The Name property is the identifier of the form in your code. For
example, if the Name of the form is Form1, you can refer to it in
the code as Form1.

• Caption:

o The Caption property sets the text that appears in the title bar
of the form when it is running. This is often used to display the
name of the application or the current state of the window.

o For example, you might set it to "Main Menu" or "User Settings."


10
NASC-B.SC(INFORMATION TECHNOLOGY)
• Icon:

o The Icon property allows you to set the small image that
appears in the upper-left corner of the window (next to the form
caption).

o You can assign your own icon (e.g., .ico files) for a personalized
appearance.

• BackColor:

o This property allows you to set the background color of the


form. The default is usually white, but you can change it to any
color you like, which helps in customizing the appearance of the
form for your application’s theme.

• MDIChild:

o When building MDI applications (Multiple Document Interface),


you can set this property to True or False.

o If set to True, the form will be treated as a child form within an


MDI parent form.

o If set to False, the form will behave as a standard, standalone


form.

o Example: In a word processor, the main window (parent) would


have child windows (documents). So, a form displaying a
document would have MDIChild = True.

3. Adding Controls to Forms

Once your form is created, you’ll often need to add various controls to
interact with the user. These controls are usually added via the Toolbox
window in VB6. The Toolbox contains a variety of commonly used controls
such as:

• TextBox:

o The TextBox control allows users to enter text. It can be used


for capturing user input, such as names, addresses, or search
queries.

o You can adjust its properties like Multiline, PasswordChar (for


password fields), and Text (the text the box will initially display).

11
NASC-B.SC(INFORMATION TECHNOLOGY)
• Label:

o The Label control is used to display static text or descriptions


on your form. Unlike a TextBox, a Label is non-editable.

o You could use labels to describe what a user needs to do, such
as "Enter your name" or "Age (in years)".

• CommandButton:

o The CommandButton control is a clickable button that triggers


an action when clicked.

o This is often used for submitting forms, navigating between


windows, or performing specific actions like “Save,” “Exit,” or
“Submit.”

o The Caption property of a CommandButton is where you set the


text that appears on the button.

• ComboBox:

o The ComboBox is a dropdown control that allows users to


choose from a list of predefined options.

o You can populate the ComboBox with a list of items via its
AddItem method or through the List property.

o It combines the functionality of a TextBox (where users can also


type custom input if required) and a ListBox (which allows users
to pick from a list).

4. Event Handling and Code

Once you’ve added controls to your form, you can write code to handle user
actions or system events (such as button clicks, form loads, or text
changes). VB6 uses a simple event-driven model, meaning that actions like
button clicks or text changes trigger specific code that you write.

Here are some basic examples of event handling:

• Button Click Event:

o Let’s say you have a CommandButton named cmdSubmit. To


handle its Click event, double-click on the button, and VB6 will
automatically generate a skeleton event handler for you. It
would look like this:
12
NASC-B.SC(INFORMATION TECHNOLOGY)
Private Sub cmdSubmit_Click()

MsgBox "You clicked the Submit button!"

End Sub

Form Load Event:

To write code that should run when the form is first loaded, you use the
Form_Load event:

Private Sub Form_Load()

Me.Caption = "Welcome to My Application" ' Set form caption

End Sub

Writing Code for Form Events

Each form has events like:

Event Description

Form_Load Occurs when the form is loaded

Form_Unload Occurs when the form is closing

Form_Activate When the form gets focus

13
NASC-B.SC(INFORMATION TECHNOLOGY)
Event Description

Form_Click When the user clicks on the form

Example:

Private Sub Form_Load()

MsgBox "Welcome to the app!"

End Sub

#4 VARIABLES

Variables in VB6 are used to store and manipulate data during the
execution of a program. They are essential for performing calculations,
storing user inputs, tracking states, etc.

1. Declaring Variables

In VB6, you declare a variable using the Dim statement:

Syntax:

Dim variablename as datatype

Example:

Dim age As Integer

Dim name As String

Dim price As Currency

2. Variable Naming Rules

• Must begin with a letter.

• Cannot use spaces or special characters (except underscore _).

• Should not be a VB6 keyword (like Dim, If, etc.).

• Should be meaningful (e.g., userName is better than x).

14
NASC-B.SC(INFORMATION TECHNOLOGY)
SCOPE OF VARIABLES

1. Local Variables

Definition:
A local variable is declared inside a procedure or function and can only be
accessed within that procedure. Once the procedure finishes execution, the
local variable goes out of scope and is destroyed.

Example:

Private Sub Command1_Click()

Dim x As Integer ' Local variable

x=5

MsgBox x ' Displaying the value of x

End Sub

• Scope: The variable x is only accessible within the Command1_Click


procedure. If you try to use x in another procedure, you will get an
error because its scope is limited to the Command1_Click method.

• Lifetime: The variable x exists only during the execution of the


Command1_Click event and is discarded once the event ends.

2. Module-Level Variables

Definition:
A module-level variable is declared outside any specific procedure, typically
at the top of a form or module, using the Private keyword. It is accessible to
all procedures within the same form or module but not outside it.

Example:

Private total As Integer ' Module-level variable

Private Sub Command1_Click()

total = 5

MsgBox total ' Displaying the module-level variable

End Sub

Private Sub Command2_Click()

total = total + 10 ' Modifying the module-level variable

15
NASC-B.SC(INFORMATION TECHNOLOGY)
MsgBox total ' Displaying updated value

End Sub

• Scope: The variable total can be accessed and modified by any


procedure within the same form or module.

• Lifetime: The value of total persists as long as the form or module is


open. It is not destroyed between procedure calls, allowing you to
retain state across multiple event triggers.

3. Global Variables

Definition:
A global variable is declared using the Public keyword in a standard module
(not in a form or class). It can be accessed from any part of the project,
including different forms or modules.

Example:

' In a standard module (e.g., Module1.bas)

Public userName As String ' Global variable

' In Form1

Private Sub Command1_Click()

userName = "JohnDoe" ' Accessing and assigning value to global variable

End Sub

' In Form2

Private Sub Command2_Click()

MsgBox userName ' Displaying the value of the global variable

End Sub

• Scope: The variable userName is accessible from any form or module


in the project, making it a global variable.

• Lifetime: The global variable exists for the duration of the entire
program and retains its value between form loads and other events.

16
NASC-B.SC(INFORMATION TECHNOLOGY)
4. Constants

Definition:
A constant is a variable-like value that cannot be changed after it is defined.
Constants are typically used for values that remain the same throughout the
program, such as mathematical values (like Pi) or application-specific
settings (like a version number).

You define a constant using the Const keyword.

Syntax:

Const constantName As DataType = value

Examples:

Const PI As Double = 3.14159

Const AppName As String = "MyVBApp"

• Scope: Constants can be declared either in a form or module (using


Private for local/module level) or in a standard module (using Public
for global scope).

• Lifetime: The value of a constant remains fixed during the entire


program's execution and cannot be modified.

Example with Constants:

Private Sub Command1_Click()

Dim radius As Double

Dim area As Double

radius = 5

area = PI * radius * radius ' Using constant PI to calculate area of a circle

MsgBox "Area of the circle: " & area

End Sub

In this example, PI is a constant, so its value (3.14159) will remain the same
throughout the program and cannot be changed.

17
NASC-B.SC(INFORMATION TECHNOLOGY)
5. Variable Visibility in Different Types of Modules

1. Form-Level (Module-Level):
Variables declared at the top of a form are accessible only within that
form (e.g., Private). They cannot be accessed by other forms unless
passed explicitly.

Example:

Private currentUser As String ' Accessible only in the current form

2. Standard Module-Level (Global):


Variables declared with the Public keyword in a standard module are
accessible across all forms and modules in the entire project.

Example in a module (Module1.bas):

Public userAge As Integer ' Accessible everywhere in the project

3. Global (Access Across Multiple Forms):


In a large project, sometimes you may want variables or settings that
can be accessed by all forms or modules. This is where global
variables (using Public in standard modules) come into play.

Key Points:

• Local variable (localCount): Only accessible within Command1_Click.

• Module-level variable (formCount): Accessible throughout the form.

• Global variable (globalCount): Accessible anywhere in the project.

• Constant (AppTitle): Cannot be changed during the program’s


execution.

#5 DATA TYPES IN VISUAL BASIC

In VB6, data types define what kind of data a variable can hold. The choice
of data type has a significant impact on the memory usage, performance,
and accuracy of your program. The correct data type ensures that your
program works efficiently, avoids errors, and helps prevent unexpected
behavior due to type mismatches.

1. Memory Efficiency:
Different data types require different amounts of memory. For
example, an Integer only uses 2 bytes, while a Double takes 8 bytes.

18
NASC-B.SC(INFORMATION TECHNOLOGY)
By choosing the appropriate data type, you can minimize the memory
usage of your program.

2. Type Safety:
VB6 will catch errors like trying to store a letter in a variable that's
meant to hold numbers. This can help prevent bugs early in
development by enforcing constraints on what can be assigned to a
variable.

3. Performance:
Choosing the right data type allows the program to perform optimally.
If you use a larger data type when a smaller one will suffice, it can
waste memory and slow down performance.

4. Readability and Maintenance:


Using the correct data type can make your code easier to read and
maintain. When others (or even yourself at a later date) read your
code, the data type can provide hints about what kind of data the
variable holds and how it should be used.

Here are the most commonly used data types in VB:

Data
Description Example
Type

Integer Whole numbers Dim x As Integer = 10

Double Decimal numbers Dim pi As Double = 3.14

String Text or alphanumeric data Dim name As String = "John"

Boolean True or False Dim isReady As Boolean = True

Date Date and time values Dim today As Date = Now

Char A single character Dim letter As Char = "A"

High-precision decimal
Decimal Dim price As Decimal = 19.99D
numbers

Dim anyValue As Object =


Object Can hold any data type
"Hello"

19
NASC-B.SC(INFORMATION TECHNOLOGY)
#6 MODULES in VB

In Visual Basic, a module serves as a container for code that can be shared
across different parts of the application. It is a file with a .bas extension (for
standard modules) that contains global variables, constants, procedures, and
functions. Modules can be used for logic that doesn't depend on the specific
form or user interface elements.

There are two primary types of modules in VB6:

1. Standard Module (.bas)

2. Class Module (.cls)

Let's look at each in more detail.

Standard Module (.bas)

A Standard Module is a regular code module that holds global data,


procedures (Subroutines and Functions), and constants. The primary
purpose of a standard module is to define general-purpose code that can be
accessed by other parts of your application, whether it's forms, other
modules, or even other projects.

Key Features:

• Global Variables: Variables declared at the module level are


accessible from anywhere in the application.

• Procedures & Functions: Code that performs actions can be grouped


in modules as reusable procedures (Sub) or functions.

• Constants: Constants that are used across the entire application can
be defined here.

• Shared Logic: Logic that needs to be used in multiple forms or areas


of the application can be stored in a module.

Example:

Module MyModule

' Global variable

Public Counter As Integer

' Constant

Public Const MaxCount As Integer = 10

20
NASC-B.SC(INFORMATION TECHNOLOGY)
' Procedure (Sub)

Sub ShowMessage()

MsgBox "Hello from the module!"

End Sub

' Function

Function IncrementCounter() As Integer

Counter = Counter + 1

Return Counter

End Function

End Module

In the example above:

• Counter is a global variable, meaning it's accessible from anywhere in


the project.

• ShowMessage is a procedure that displays a message box when


called.

• IncrementCounter is a function that increments the Counter variable


and returns the updated value.

Why Use a Standard Module?

• Reusability: Code in a module can be reused by different forms and


parts of your application.

• Organization: It helps organize code into logical units. For example,


you might have a module for database handling, another for utility
functions, and another for global variables.

• No Tied to a Form: Unlike forms and controls, modules aren't tied to


any visual UI components. This makes modules great for backend or
shared logic.

Class Module (.cls)

A Class Module defines a custom object, with its own properties, methods,
and events. You can think of it as defining your own type of object with
certain behavior and state. Class modules are used when you need to model
real-world entities or need encapsulation for data and behavior.

21
NASC-B.SC(INFORMATION TECHNOLOGY)
Key Features:

• Properties: Variables that belong to the object and represent its state.

• Methods: Functions or subroutines that define what the object can


do.

• Events: Allows the class to notify other parts of the application when
certain actions occur.

Why Use Class Modules?

• Object-Oriented Design: Class modules follow the principles of


object-oriented programming (OOP) and allow you to define custom
objects that represent real-world entities.

• Encapsulation: Data (properties) and behavior (methods) are bundled


together, making the code cleaner and more maintainable.

• Reusability and Extensibility: Once you define a class, it can be


instantiated (used) multiple times in different parts of the project.

Advantages of Using Modules in VB6:

1. Global Scope: Variables and functions in modules are accessible


across the entire project.

2. Code Organization: Modules help you logically separate your code


(e.g., a module for handling files, another for data processing).

3. Simplicity: Standard modules are simple and don't require object-


oriented concepts like classes. This can be especially useful for small
to medium-sized projects.

4. Reusability: Once written, a module can be reused throughout your


application, reducing code duplication.

#7 PROCEDURES in VB

In VB6 (Visual Basic 6.0), procedures are blocks of code that perform
specific tasks, and they help to modularize and organize your program.
Procedures can be called to execute their instructions from anywhere in
your code.

1. Sub Procedures

A Sub Procedure (or simply a Sub) is a block of code that performs a specific
task but does not return a value. It is used to execute operations, like

22
NASC-B.SC(INFORMATION TECHNOLOGY)
displaying a message, updating a variable, or manipulating a control,
without providing a result to the caller.

Key Points about Sub Procedures:

• No return value: A subroutine does not return any data.

• It can accept parameters that provide input to the procedure.

• You call a subroutine to perform a task, but the subroutine doesn’t


provide any output.

Syntax for Sub Procedure:

Sub SubProcedureName()

…..

End Sub

Sub Procedure with Arguments:

You can define arguments in a Sub procedure to allow it to accept input


when called.

Sub ShowMessage(ByVal message As String)

MsgBox message

End Sub

Calling the Sub Procedure:

ShowMessage "Hello from the Sub!"

The above ShowMessage subroutine displays a message box when called,


but it doesn’t return anything to the caller.

2. General Procedures

In VB6, the term General Procedure is typically used to refer to procedures


(both Sub Procedures and Function Procedures) that can be defined globally
and used throughout the program. A General Procedure can be either a Sub

23
NASC-B.SC(INFORMATION TECHNOLOGY)
or a Function, and the term "general" simply refers to it being a reusable
piece of code that can be placed in Standard Modules or Class Modules.

A general procedure can be used for general tasks that are not tied to any
specific form or control.

General Procedure Syntax:

• Sub Procedure (no return value):

Sub GeneralSub()

' Perform actions

End Sub

• Function Procedure (with return value):

Function GeneralFunction() As Integer

' Perform actions and return a value

GeneralFunction = 10

End Function

These general procedures can be placed in Standard Modules and can be


accessed throughout the project.

3. Function Procedures

A Function Procedure (or simply a Function) is a block of code that performs


a task and returns a value to the caller. Functions are useful when you need
to calculate something or return data based on some logic.

Key Points about Function Procedures:

• Returns a value: A function will return a value to the caller. You


specify the return type when declaring the function.

• Can accept parameters: A function can take parameters, just like a


Sub procedure.

• Used in expressions: Because functions return a value, you can call


them directly in an expression or assign their result to a variable.

24
NASC-B.SC(INFORMATION TECHNOLOGY)
Syntax for Function Procedure:

Function FunctionName() As
DataType

…….

End Function

Function with Parameters:

Function AddNumbers(ByVal num1 As Integer, ByVal num2 As Integer) As


Integer

AddNumbers = num1 + num2

End Function

Calling a Function Procedure:

You can call a function and assign its return value to a variable.

Dim result As Integer

result = AddNumbers(5, 3)

MsgBox "The result is " & result

The AddNumbers function adds two numbers and returns the result, which
is then displayed in a message box.

4. Property Procedures

Property Procedures are used in Class Modules to define how you can get or
set the value of an object’s property. Property procedures are a special type
of function and subroutine that enable you to encapsulate the access to an
object’s data.

There are three types of property procedures:

1. Property Get: Used to retrieve a property value.

2. Property Let: Used to assign a value to a property (for non-object


properties).
25
NASC-B.SC(INFORMATION TECHNOLOGY)
3. Property Set: Used to assign an object reference to a property.

Key Points about Property Procedures:

• Property Get: Retrieves a property value.

• Property Let: Assigns a value to a property (used with non-object


types).

• Property Set: Assigns an object reference to a property (used with


object types).

#8 CONTROL STRUCTURES in VB

Control structures in VB6 (Visual Basic 6.0) are essential constructs


that allow you to control the flow of your program's execution. These
structures determine how your program makes decisions, repeats tasks, or
chooses between alternative actions.

There are several types of control structures in VB6, including decision


making statements, loops, and sequential.

1. Decision making Statements

Conditional statements allow your program to make decisions and execute


different code depending on whether a condition is true or false.

1.1. If...Then...Else

The If...Then...Else statement is the most commonly used control structure


for conditional logic. It checks if a condition is true and then runs one block
of code. If the condition is false, it runs an alternative block (in the Else
part).

Syntax:

If condition Then

' Code to execute if condition is True

Else

' Code to execute if condition is False

End If

Example:

Dim age As Integer

26
NASC-B.SC(INFORMATION TECHNOLOGY)
age = 18

If age >= 18 Then

MsgBox "You are an adult."

Else

MsgBox "You are a minor."

End If

In this example, the program checks whether the age is 18 or greater. If


true, it displays "You are an adult"; otherwise, it displays "You are a minor."

1.2. If...Then (Without Else)

If you don’t need an Else part, you can use a simplified If...Then statement.

Syntax:

If condition Then

' Code to execute if condition is True

End If

Example:

Dim number As Integer

number = 5

If number > 0 Then

MsgBox "The number is positive."

End If

1.3. ElseIf

You can use ElseIf to check multiple conditions within the same If block.

Syntax:

27
NASC-B.SC(INFORMATION TECHNOLOGY)
If condition1 Then

' Code to execute if condition1 is True

ElseIf condition2 Then

' Code to execute if condition2 is True

Else

' Code to execute if all conditions are False End If

Example:

Dim score As Integer

score = 85

If score >= 90 Then

MsgBox "A grade"

ElseIf score >= 80 Then

MsgBox "B grade"

ElseIf score >= 70 Then

MsgBox "C grade"

Else

MsgBox "Fail"

End If

Here, the program checks for multiple conditions and provides a grade
based on the score.

2. Select Case

The Select Case statement is an alternative to multiple If...ElseIf...Else


statements when you want to check a single expression against multiple
possible values.

Syntax:

28
NASC-B.SC(INFORMATION TECHNOLOGY)
Select Case expression

Case value1

' Code if expression = value1

Case value2

' Code if expression = value2

Case Else

' Code if none of the cases match

End Select

Example:

Dim day As Integer

day = 3

Select Case day

Case 1

MsgBox "Monday"

Case 2

MsgBox "Tuesday"

Case 3

MsgBox "Wednesday"

Case 4

MsgBox "Thursday"

Case Else

MsgBox "Invalid day"

End Select

In this example, Select Case checks the value of day and displays the
corresponding message for the day of the week.

3. Looping Structures

29
NASC-B.SC(INFORMATION TECHNOLOGY)
Loops are used to execute a block of code repeatedly as long as a certain
condition is met.

3.1. For...Next Loop

The For...Next loop is used when you know in advance how many times you
want to repeat a block of code.

Syntax:

For counter = start To end [Step step]

' Code to execute

Next counter

• start is the initial value of the counter.

• end is the final value the counter should reach.

• step is the increment by which the counter changes each time


(optional, default is 1).

Example:

For i = 1 To 5

MsgBox "Iteration " & i

Next i

In this example, the loop runs 5 times and displays a message box with the
current iteration number.

3.2. For Each...Next Loop

The For Each...Next loop is used to iterate over a collection or array.

Syntax:

For Each item In collection

' Code to execute for each item

Next item

Example:

Dim names(3) As String

names(0) = "John"

names(1) = "Jane"

30
NASC-B.SC(INFORMATION TECHNOLOGY)
names(2) = "Paul"

For Each name In names

MsgBox name

Next name

Here, the loop iterates over the names array and displays each name in a
message box.

3.3. Do...Loop

The Do...Loop allows you to repeat code while a condition is true or until a
condition becomes true. You can control the loop with the While or Until
condition.

Syntax:

Do

' Code to execute

Loop While condition

Example:

Dim counter As Integer

counter = 1

Do

MsgBox "Counter is " & counter

counter = counter + 1

Loop While counter <= 5

This loop will continue until the counter exceeds 5.

31
NASC-B.SC(INFORMATION TECHNOLOGY)
ARRAYS

In VB6, arrays are used to store multiple values of the same type in a
single variable. Arrays are particularly useful when you need to work with a
list of similar data types, such as a list of numbers or strings, and you want
to access them by index.

An array is a collection of variables (elements) that are all of the same


type (e.g., Integer, String, etc.) and are stored under a single variable name.
You can access each element using an index (starting from 0 or another
base depending on how it's defined).

Types of Arrays in Vb6

There are two primary types of arrays in VB6:

1. Fixed size Arrays: These have a fixed size, which is defined at the time
of declaration and cannot be changed.

2. Dynamic Arrays: These can change size during runtime using the
ReDim statement.

3. Multidimensional array: a multidimensional is used when we need to


represent information of different dimensions.

1. Fixed size Arrays

A static array has a predefined size, which is set at the time of declaration
and cannot be changed during execution.

Syntax:

Dim arrayName(size) As DataType

Where:

• arrayName is the name of the array.

• size is the number of elements in the array (starting index is 0, so if


size = 5, you can store 5 elements at indices 0 to 4).

• DataType is the type of data the array will hold (e.g., Integer, String,
etc.).

Example:

Dim numbers(4) As Integer ' Array with 5 elements (indices 0 to 4)

numbers(0) = 10
32
NASC-B.SC(INFORMATION TECHNOLOGY)
numbers(1) = 20

numbers(2) = 30

numbers(3) = 40

numbers(4) = 50

In this example:

• numbers is an array that can hold 5 integers (index 0 to 4).

• Each element is assigned a value.

2.Dynamic Arrays

A dynamic array does not have a fixed size at the time of declaration. You
can use the ReDim statement to define the array's size later, during
runtime. Additionally, you can change the size of the array using ReDim
whenever necessary.

Syntax for Declaring a Dynamic Array:

Dim arrayName() As DataType ' No size is specified.

Syntax for Redimensioning a Dynamic Array:

ReDim arrayName(newSize)

Example:

Dim numbers() As Integer ' Dynamic array, no size specified

' Later in the code, define the size

ReDim numbers(4) ' Array can now hold 5 elements (indices 0 to 4)

numbers(0) = 10

numbers(1) = 20

numbers(2) = 30

numbers(3) = 40
33
NASC-B.SC(INFORMATION TECHNOLOGY)
numbers(4) = 50

You can also use the Preserve keyword to retain the values of the array
when resizing it:

ReDim Preserve numbers(9) ' Resize array to 10 elements, keeping previous


values

Accessing Array Elements

You can access individual elements of an array using the index (starting
from 0). The general syntax is:

SYNTAX

arrayName(index)

For example, to access the 3rd element in an array:

Dim numbers(4) As Integer

numbers(0) = 10

numbers(1) = 20

numbers(2) = 30

numbers(3) = 40

numbers(4) = 50

MsgBox numbers(2) ' Displays 30 (the 3rd element)

3.Multidimensional Arrays

In addition to one-dimensional arrays, VB6 supports multidimensional


arrays (such as 2D, 3D, etc.), where you can store data in a table-like
structure (rows and columns).

Declaring a 2D Array (2-Dimensional Array)

34
NASC-B.SC(INFORMATION TECHNOLOGY)
A 2D array is essentially an array of arrays. You can think of it as a table
with rows and columns.

Syntax:

Dim arrayName(rowSize, columnSize) As DataType

Example:

Dim matrix(2, 3) As Integer ' A 3x4 matrix (3 rows, 4 columns)

' Assigning values

matrix(0, 0) = 1

matrix(0, 1) = 2

matrix(0, 2) = 3

matrix(0, 3) = 4

matrix(1, 0) = 5

matrix(1, 1) = 6

matrix(1, 2) = 7

matrix(1, 3) = 8

matrix(2, 0) = 9

matrix(2, 1) = 10

matrix(2, 2) = 11

matrix(2, 3) = 12

' Accessing an element

MsgBox matrix(1, 2) ' Displays 7 (2nd row, 3rd column)

#9 WORKING WITH CONTROLS:

Controls are UI elements that allow users to interact with your


application — for example, buttons, labels, textboxes, combo boxes, and
so on.

35
NASC-B.SC(INFORMATION TECHNOLOGY)
How to Create and Use Controls in Visual Basic

1. Using the Toolbox (Design View)

In Visual basic 6.0:

• Open your form (e.g., Form1.vb).

• Go to View > Toolbox (if not already open).

• Drag a control (e.g., a Button) onto the form.

2. Set Properties

Use the Properties Window to change settings like:

Property Description Example

Name The internal name used in code btnSubmit

Text The text shown to the user "Submit"

BackColor Background color LightBlue

Enabled Enables/disables the control True / False

Visible Shows/hides the control True / False

3. Adding Event Handlers (Code Behind)

To write code for a control (e.g., when a button is clicked):

• Double-click the control on the form.

• Visual Studio will open the Code Editor and create an event
procedure.

Example: Button Click

Design:

Add:

• A Button (Name: btnGreet)

• A TextBox (Name: txtName)

• A Label (Name: lblGreeting)

Code:

36
NASC-B.SC(INFORMATION TECHNOLOGY)
Private Sub btnGreet_Click(sender As Object, e As EventArgs) Handles
btnGreet.Click

Dim name As String = txtName.Text

lblGreeting.Text = "Hello, " & name & "!"

End Sub

When the button is clicked, it reads text from txtName and shows a greeting
in lblGreeting.

Commonly Used Controls

Control Purpose

Label Display text

TextBox User input

Button Trigger actions

CheckBox True/False selection

RadioButton Choose one of multiple options

ComboBox Dropdown selection

ListBox List of items

PictureBox Display images

Timer Perform repeated actions over time

Label Control?

• A Label (class System.Windows.Forms.Label) is a read-only text


display element, primarily used to show captions or descriptive text on
a form

• Generally static — users can’t edit it or focus on it (unless it's a


special LinkLabel) .

Key Properties
37
NASC-B.SC(INFORMATION TECHNOLOGY)
Property Description

The text displayed — can be set at design time or


Text
runtime

Automatically adjusts control size to fit text


AutoSize
(True/False) .

Determines the border: None, FixedSingle, or


BorderStyle
Fixed3D .

Font Font family/size/style for the text .

ForeColor Text color .

BackColor Background color (useful with opaque style) .

Alignment within the control (TopLeft, MiddleCenter,


TextAlign
etc.) .

FlatStyle Appearance style (Flat, Popup, Standard) .

PreferredWidth/Height Read-only: gives optimal size based on text/font .

Image & ImageAlign Display an image alongside text .

Whether to interpret “&” as keyboard access keys


UseMnemonic
(e.g., ALT + letter) .

TextBox control:

The TextBox control (class System.Windows.Forms.TextBox) allows users to


enter and edit text. It supports single-line or multi-line input, with optional
scrolling, password masking, and formatting features.

Key Properties

• Text: The current text displayed; you can get or set it in code or via
the Properties window .

• Multiline (Boolean): Enables multiple lines (default is False).

• MaxLength (Integer): Limits characters user can enter (default up to


32,767).

38
NASC-B.SC(INFORMATION TECHNOLOGY)
• PasswordChar (Char): Masks entered text, e.g.,
TextBox1.PasswordChar = "*",.

• TextAlign: Horizontal alignment of text: Left, Right, or Center .

• CharacterCasing: Auto-convert input to Normal, Upper, or Lower case

Button Control?

A Button (class System.Windows.Forms.Button) is a standard clickable


element used to initiate actions—such as opening dialogs, submitting forms,
or running code. It responds to mouse clicks or keyboard actions like
Enter/Space when focused

Property Description

Text The caption shown on the button.

Name Identifier used in code (e.g., btnSubmit) .

True to allow interaction, False to disable


Enabled
(grayed out) .

Visible Controls visibility on the form .

BackColor/ForeColor Sets background and text colors .

Allows custom fonts and images on the


Font/Image/BackgroundImage
button .

AutoSizeMode Enables automatic sizing to fit content .

Useful for dialog forms: sets a value (like


DialogResult
DialogResult.OK) returned when clicked .

AllowDrop Enables drag-and-drop support .

Position on the form and tab navigation


Location/TabIndex
order .

39
NASC-B.SC(INFORMATION TECHNOLOGY)
Control Array (VB6 Style)

A Control Array in Visual Basic 6 (VB6) is a set of controls of the same type
(e.g., multiple TextBox, CommandButton, Label, etc.) that:

• Share the same name

• Are differentiated by an Index value

• Share a single event handler, simplifying your code

This makes your code more efficient and maintainable, especially when
handling groups of similar controls.

Creating Control Arrays

1. At Design Time

1. Place a control (e.g., Command1) on your form.

2. Copy it (Ctrl+C) and paste it (Ctrl+V).

3. VB6 asks: "Do you want to create a control array?"

4. Click Yes.

Now you have:

• Command1(0)

• Command1(1)

2.Runtime Control Arrays

A runtime control array means that additional controls are added to the
array while the program is running, instead of placing all of them on the
form at design time.

To dynamically generate UI elements based on user actions or data

To save design time when the number of controls needed isn't known
in advance

To keep code clean and organized by using shared event procedures

Prerequisites for Runtime Control Arrays

1. At least one control of the desired type (e.g., TextBox) must be added
to the form at design time.

2. Set the Index property to 0 to make it part of a control array.

40
NASC-B.SC(INFORMATION TECHNOLOGY)
The Load Statement

The Load statement is used to create new instances of a control in the


array:

Load Text1(1)

• This creates a new TextBox with index 1.

• By default, loaded controls are not visible — you must set .Visible =
True.

Example of Creating Controls at Runtime

Load Text1(1)

Text1(1).Visible = True

Text1(1).Top = Text1(0).Top + Text1(0).Height + 100

Text1(1).Left = Text1(0).Left

This code:

• Creates a new TextBox Text1(1)

• Sets its position below Text1(0)

• Makes it visible

Event Handling

All controls in a control array share the same event procedures, with the
Index used to differentiate them.

Example:

Private Sub Text1_Change(Index As Integer)

MsgBox "You typed in Text1(" & Index & ")"

End Sub

41
NASC-B.SC(INFORMATION TECHNOLOGY)
EXPECTED QUESTIONS:

1 marks

1. Which of the following is the default extension for a Visual Basic 6 project
file?
A) .vbp
B) .exe
C) .vb6
D) .vbg
Answer: A) .vbp
2. Which of the following is used to declare a variable in VB6?
A) Var
B) Dim
C) Declare
D) Set
Answer: B) Dim
3. What type of control is used to display a message to the user in VB6?
A) TextBox
B) Label
C) Button
D) ComboBox
Answer: B) Label
4. Which of the following data types is used to store decimal numbers in
VB6?
A) Integer
B) Single
C) String
D) Boolean
Answer: B) Single
5. Which control property allows you to change the text displayed on a
button in VB6?
A) Name
B) Text
C) Caption
D) Font
Answer: C) Caption
6. What is the purpose of an Option Explicit statement in VB6?
A) It declares all variables.
B) It forces the use of error handling.
C) It specifies the default data type.
D) It disables the use of MsgBox.
Answer: A) It declares all variables.

5 MARKS

1. Explain the steps involved in creating a simple VB6 application.

2. Describe different types of procedures in VB6 with examples.

42
NASC-B.SC(INFORMATION TECHNOLOGY)
3. Write a short note on control arrays. How are they created and
accessed?

4. Differentiate between module-level and global-level variables with


examples.

5. Briefly explain various data types supported by VB6.

8 MARKS

1. Describe the VB6 Integrated Development Environment (IDE) with the


help of a labeled diagram and explain each component.

2. Write a VB6 program that takes input from the user through a form
and calculates the factorial of a number using a loop.

3. Discuss various control structures in VB6 with suitable code


examples (e.g., If...Then, Select Case, For...Next).

4. Explain how arrays are declared and used in VB6. Write a program to
find the largest number in an array of integers entered by the user.

43
NASC-B.SC(INFORMATION TECHNOLOGY)
Unit:2 MENUS IN VB 15
hours
#1 Menus,#2 Mouse events and #3 Dialog boxes: Mouse events, Dialog boxes, MDI
and Flex grid: #4 MDI, #5 Using the Flex grid control.

INTRODUCTION:

#1 Menu:

Menus are an integral part of Windows Forms applications, providing users


with a way to interact with the program by selecting various options. In VB6,
you can create menus using the Menu Editor. Menus usually contain a list
of commands (or menu items) that a user can select to perform specific
actions like open a file, exit the application, etc.

In VB6, menus are part of the main menu bar that is typically located at the
top of a form. You can use Menu Editor to easily design and manage menus
in your application.

How to Create a Menu in VB6 Using Menu Editor:

The Menu Editor in VB6 is a tool that allows you to add, arrange, and define
actions for various menus and menu items without needing to manually
code the interface. Here’s a step-by-step guide to creating menus using the
Menu Editor:

Step 1: Open Menu Editor

1. Launch Visual Basic 6.0 and open your project (or create a new
project).

2. On the Form Designer window, go to the Tools menu at the top of the
screen.

3. Click on Menu Editor, or alternatively, press Ctrl + E. This will open


the Menu Editor window.

44
NASC-B.SC(INFORMATION TECHNOLOGY)
Step 2: Define Your Main Menu (Caption and Name)

• In the Menu Editor, you’ll need to define main menus first. These are
the primary categories that appear on the top menu bar (e.g., File,
Edit, Help).

1. Caption: This is the text that will appear on the menu bar.

For example, in the File menu, the caption would be "File".

2. Name: This is the identifier used in the code. This name allows you to
reference the menu programmatically, i.e., when writing the code that
responds to user actions like clicks on the menu items.

For example, the name for the File menu might be mnuFile.

Step 3: Add Menu Items (Submenu Items)

Each main menu can have multiple submenus (also known as menu items)
that represent the actions a user can take. For example, the File menu can
contain items like New, Open, and Exit.

1. In the Menu Editor, click on the main menu item (e.g., File) to select
it.

2. To add a submenu item, click on the Insert button (or press the Insert
key), which will allow you to define an item under the selected menu.

45
NASC-B.SC(INFORMATION TECHNOLOGY)
3. You’ll need to specify the caption (what will be displayed on the menu
item) and the name (the identifier that will be used in the code).

• For example:

o Caption for a submenu might be "New" or "Open".

o Names could be mnuNew or mnuOpen.

Example:

Menu Layout (Hierarchy)

File

├── New

├── Open

└── Exit

Here, "File" is the main menu, and "New", "Open", and "Exit" are the
submenu items.

Access keys :

Access key allows you to open a menu by pressing the alt key and then the
designated letter. Access key also allow the user to access menu command
once the menu is open by continuing to hold the alt key and pressing its
designated letter.

46
NASC-B.SC(INFORMATION TECHNOLOGY)
Shortcuts:

Shortcut is different they run a menu command immediately after the


shortcut is pressed.

#2 MOUSE EVENTS:

What is a Mouse Event?

In VB.NET, mouse events are used to capture and respond to user


interactions with mouse devices, such as clicking, moving, hovering, or
scrolling. These events help developers create interactive applications with
customized behavior for mouse actions.

Types of Mouse Events in VB.NET

Each of the mouse events in VB.NET provides a specific way to respond to


user input. Here’s an explanation of each event:

MouseClick

Description: This event is triggered when a mouse button is clicked


(pressed and released) over a control.

Usage: It's commonly used when you want to perform an action when the
user clicks on a control like a button or a label.

47
NASC-B.SC(INFORMATION TECHNOLOGY)
Example:

Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs)

MessageBox.Show("Button clicked at coordinates: " & e.X & ", " & e.Y)

End Sub

MouseDown

Description: This event occurs when a mouse button is pressed down,


before it is released.

Usage: You can use this event to detect when the user starts interacting
with a control (e.g., starting a drag operation).

Example:

Private Sub Button1_MouseDown(sender As Object, e As MouseEventArgs)

If e.Button = MouseButtons.Left Then

MessageBox.Show("Left button pressed.")

End If

End Sub

MouseUp

Description: This event occurs when a mouse button is released after being
pressed.

Usage: It’s used in conjunction with MouseDown to implement drag-and-


drop operations or detect when a user finishes an action (like a drag).

Example:

Private Sub Button1_MouseUp(sender As Object, e As MouseEventArgs)


Handles Button1.MouseUp

MessageBox.Show("Mouse button released.")

End Sub

MouseMove

Description: This event is triggered whenever the mouse pointer is moved


over a control or form.

Usage: It’s commonly used for real-time tracking of the mouse or updating
the UI dynamically based on the pointer's position.

48
NASC-B.SC(INFORMATION TECHNOLOGY)
Example:

Private Sub Button1_MouseMove(sender As Object, e As MouseEventArgs)

Label1.Text = "Mouse Position: " & e.X & ", " & e.Y

End Sub

MouseEnter

Description: This event occurs when the mouse pointer enters the bounds
of a control.

Usage: This is useful for changing the appearance of a control when the
user hovers over it (e.g., highlighting a button when the user hovers over it).

Example:

Private Sub Button1_MouseEnter(sender As Object, e As EventArgs) Handles


Button1.MouseEnter

Button1.BackColor = Color.AliceBlue

End Sub

MouseLeave

Description: This event occurs when the mouse pointer leaves the bounds
of a control.

Usage: It's commonly used to reset the control's appearance when the
mouse leaves the control (e.g., unhighlighting a button).

Example:

Private Sub Button1_MouseLeave(sender As Object, e As EventArgs) Handles


Button1.MouseLeave

Button1.BackColor = Color.White

End Sub

MouseHover

Description: This event is triggered when the mouse pointer rests on a


control for a short period of time (e.g., hovering over a button).

Usage: It's commonly used for showing tooltips or initiating custom actions
when a user pauses over a control.

49
NASC-B.SC(INFORMATION TECHNOLOGY)
Example:

Private Sub Button1_MouseHover(sender As Object, e As EventArgs)


Handles Button1.MouseHover

ToolTip1.SetToolTip(Button1, "Click to perform an action.")

End Sub

MouseWheel

Description: This event is triggered when the scroll wheel on the mouse is
moved (up or down).

Usage: You can use this event for implementing zoom-in/zoom-out


functionality or scrolling within a control (like a picture box or a scrollable
form).

Example:

Private Sub Form1_MouseWheel(sender As Object, e As MouseEventArgs)


Handles Me.MouseWheel

If e.Delta > 0 Then

MessageBox.Show("Mouse wheel scrolled up")

Else

MessageBox.Show("Mouse wheel scrolled down")

End If

End Sub

MouseEventArgs Class

The MouseEventArgs class provides detailed information about the mouse


event. It contains several properties that are useful for handling mouse
interactions:

• Button: Identifies which mouse button was pressed. It returns a value


from the MouseButtons enumeration (e.g., MouseButtons.Left,
MouseButtons.Right, MouseButtons.Middle).

• Clicks: Returns the number of times the mouse button has been
clicked (useful for double-click detection).

• X, Y: The X and Y coordinates of the mouse pointer relative to the top-


left corner of the control (or form) when the event occurs.

50
NASC-B.SC(INFORMATION TECHNOLOGY)
• Delta: The amount the mouse wheel has moved. The value is positive
when the wheel is scrolled up and negative when it is scrolled down.

Event Handling Process in VB.NET

Here’s a breakdown of how you handle mouse events in VB.NET:

1. Select the Control: Choose a control (e.g., Button, Form, PictureBox)


that you want to respond to mouse events.

2. Attach the Event: In the Properties Window or in your code, attach


an event handler for the desired mouse event (like MouseClick,
MouseMove, etc.).

3. Write Code Inside the Event Handler: Define the functionality you
want to happen when the event occurs. This can include any
interaction with the form, updating the UI, or invoking custom logic
based on mouse position or actions.

#3 DIALOG BOX

A dialog box is a small window that pops up to:

• Get input from the user

• Show messages or information

• Allow users to open/save files, pick colors, select fonts, etc.

Dialog boxes are part of the Graphical User Interface (GUI) in VB.NET and
are used for interactive communication between the program and the
user.

Types of Dialog Boxes in VB.NET

1. MessageBox

• Displays messages or prompts.

• Can show info, warnings, errors, or ask questions.

51
NASC-B.SC(INFORMATION TECHNOLOGY)
2. Common Dialog Boxes

These are predefined in the System.Windows.Forms namespace and


include:

Dialog Box Purpose

OpenFileDialog Open a file from disk

SaveFileDialog Save a file to disk

ColorDialog Pick a color

FontDialog Choose a font style

FolderBrowserDialog Select a folder

52
NASC-B.SC(INFORMATION TECHNOLOGY)
3. Custom Dialog Box

• A form designed by the programmer to get specific input.

• Can contain any control like TextBox, ComboBox, etc.

Common Dialog Box Classes (Built-in)

Dialog Box Class Name

Message Box MessageBox

Open File Dialog OpenFileDialog

Save File Dialog SaveFileDialog

Color Dialog ColorDialog

Font Dialog FontDialog

Folder Dialog FolderBrowserDialog

MessageBox – Example and Syntax

MessageBox.Show("This is a message.", "Title",


MessageBoxButtons.OKCancel, MessageBoxIcon.Information)

Parameters:

• Text – Message to show

53
NASC-B.SC(INFORMATION TECHNOLOGY)
• Caption – Title of the box

• Buttons – OK, Cancel, Yes/No, etc.

• Icon – Information, Warning, Error

OpenFileDialog – Example

Dim ofd As New OpenFileDialog()

ofd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"

If ofd.ShowDialog() = DialogResult.OK Then

MessageBox.Show("Selected file: " & ofd.FileName)

End If

# 4 MDI forms

• MDI stands for Multiple Document Interface.

• It allows a single parent window (MDI Form) to contain multiple child


forms (MDI Child Forms).

• All child forms are confined within the parent window and cannot
move outside of it.

54
NASC-B.SC(INFORMATION TECHNOLOGY)
Types of Forms in MDI Applications

MDI Parent Form:

o Acts as a container for child forms.

o Created by setting the form's MDIChild property to False.

o You create an MDI Parent Form by choosing "MDI Form" in VB6


(not a regular form).

MDI Child Forms:

o These are regular forms, but with the MDIChild property set to
True.

o They must be shown inside the MDI parent form.

3. Creating an MDI Application in VB6

Steps:

1. Add an MDI Form to your project:

o Project → Add MDI Form.

2. Add a regular Form and set it as a child:

o Open the form’s properties and set MDIChild = True.

3. Show the child form from the MDI form using code like:

Private Sub mnuOpenForm_Click()

Load frmChild

frmChild.Show

End Sub

Important Properties and Methods

Property/Method Description

MDIChild Set to True to make a form a child form.

Parent Refers to the MDI Parent Form.

ActiveForm Returns the currently active MDI child.

55
NASC-B.SC(INFORMATION TECHNOLOGY)
Property/Method Description

Used to arrange child forms (vbCascade, vbTileHorizontal,


Arrange
vbTileVertical).

Example:

MDIForm1.Arrange vbCascade

Advantages of MDI Applications

• Centralized management of multiple forms.

• Easier to implement document-based interfaces.

• Clean, unified user interface for handling related data.

# 5 FlexGrid control:

• A read-only grid control used to display data in a tabular format.

• Does not allow direct editing of cell contents (unlike MS DataGrid).

• Useful for displaying data from databases, arrays, or hardcoded


values.

Control name in Toolbox: MSFlexGrid

To use it:
Project → Components → Microsoft FlexGrid Control 6.0 (SP6)

2. Key Properties of FlexGrid

Property Description

Rows Sets or returns the total number of rows.

Sets or returns the total number of


Cols
columns.

TextMatrix(Row, Col) Gets or sets the text of a specific cell.

Indicates the current row and column


Row / Col
selected.

56
NASC-B.SC(INFORMATION TECHNOLOGY)
Property Description

Defines headers that stay fixed while


FixedRows / FixedCols
scrolling.

ColWidth(col) Sets the width of a column.

RowHeight(row) Sets the height of a row.

CellBackColor / Sets the background or text color of a


CellForeColor cell.

3. Basic Example – Populating a FlexGrid

Private Sub Form_Load()

With MSFlexGrid1

.Rows = 5

.Cols = 3

.TextMatrix(0, 0) = "ID"

.TextMatrix(0, 1) = "Name"

.TextMatrix(0, 2) = "Age"

.TextMatrix(1, 0) = "101"

.TextMatrix(1, 1) = "Alice"

.TextMatrix(1, 2) = "25"

.TextMatrix(2, 0) = "102"

.TextMatrix(2, 1) = "Bob"

.TextMatrix(2, 2) = "30"

End With

End Sub

57
NASC-B.SC(INFORMATION TECHNOLOGY)
OUTPUT:

4. Common Uses

• Displaying results from a database query.

• Creating a report-style view of data.

• Showing data where user interaction is limited to selection only.

QUESTIONS

1 marks

Which of the following is a valid mouse event in VB6?


A) MouseClick
B) MouseMove
C) MouseDown
D) All of the above
Answer: D) All of the above

In VB6, which of the following controls is used to create menus in an MDI


form?
A) MenuStrip
B) MDIChild
C) MenuEditor
D) Menu
Answer: C) MenuEditor

58
NASC-B.SC(INFORMATION TECHNOLOGY)
Which property of the FlexGrid control is used to set the number of rows in
the grid?
A) RowCount
B) ColumnCount
C) Row
D) Cells
Answer: A) RowCount

Which dialog box is used to allow the user to select a file in VB6?
A) ColorDialog
B) FileOpenDialog
C) FileDialog
D) CommonDialog
Answer: C) FileDialog

What is the default property of a FlexGrid control in VB6?


A) Text
B) Value
C) TextMatrix
D) Cells
Answer: C) TextMatrix

What is the default behavior of the MDI form in VB6?


A) It displays only one child form.
B) It allows multiple child forms to be displayed at the same time.
C) It doesn’t allow any child form.
D) It opens a menu automatically.
Answer: B) It allows multiple child forms to be displayed at the same time.

Which event is triggered when the mouse pointer is moved over a control in
VB6?
A) MouseClick
B) MouseMove
C) MouseEnter
D) MouseDown
Answer: B) MouseMove

What does the Show method of the CommonDialog control do in VB6?


A) It displays a file dialog.
B) It opens the main form.
C) It hides the form.
D) It sets a color.
Answer: A) It displays a file dialog.

Which of the following is NOT a type of dialog box in VB6?


A) FileSave
B) Color
C) Print

59
NASC-B.SC(INFORMATION TECHNOLOGY)
D) Form
Answer: D) Form

Which property of the MDI form defines whether a form can be maximized?
A) Maximized
B) WindowState
C) FormStyle
D) AutoResize
Answer: B) WindowState

5 marks:

1. Explain different types of mouse events in VB6 with examples.

2. Write a short note on common dialog boxes available in VB6.

3. What is an MDI form? How does it differ from a standard form in VB6?

4. List and describe any five properties of the FlexGrid control.

5. How are menus created in VB6? Write steps and an example to create
a simple menu.

Eight Mark Questions

1 .Describe the process of creating a menu in VB6 using the Menu Editor.
Write a program that implements a menu with submenus and shortcut
keys.

2.Explain the different mouse events (MouseDown, MouseUp, MouseMove)


with a program that tracks mouse position and button clicks.

3.What is MDI (Multiple Document Interface)? Explain how to create an MDI


application with multiple child forms and demonstrate inter-form
communication.

4.Explain the use of the MSFlexGrid control in VB6. Write a program to


display a list of student names and marks in a FlexGrid and calculate total
and average.

60
NASC-B.SC(INFORMATION TECHNOLOGY)

You might also like