0% found this document useful (0 votes)
8 views35 pages

VB_NET_5th_Sem_10_Questions_Handwritten_Style

notes

Uploaded by

capiy33900
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)
8 views35 pages

VB_NET_5th_Sem_10_Questions_Handwritten_Style

notes

Uploaded by

capiy33900
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

VB.

NET – BCA 5th Sem

Important 10 Questions (Handwritten Style Notes)

■ Solve any 5 out of 10 – Each question carries 10 marks.

Prepared for: DBRAU BCA 5th Semester Exam


■ Q1 – 10 Marks (5■Page Exam Standard Answer) Explain the architecture of
the .NET Framework. Describe CLR, CTS, CLS and FCL in detail.

Introduction The .NET Framework is a software development platform developed by Microsoft. It


provides a managed execution environment, large class libraries, and supports multiple programming
languages like VB.NET, C#, etc. The framework is mainly used to build Windows, Web, and enterprise
applications. Its architecture is designed to give security, performance, language interoperability,
memory management, and error handling in an organized manner.

■ Architecture of .NET Framework The architecture is divided into several important components:

1. Common Language Runtime (CLR) CLR is the main execution engine of .NET. It manages the
complete life cycle of a .NET application.

Functions of CLR: (a) Memory Management CLR handles memory allocation and deallocation
automatically. It contains a Garbage Collector (GC) which removes unused objects and frees memory.

(b) Exception Handling .NET uses a unified exception-handling model which makes it easier to debug
and maintain applications.

(c) JIT Compilation VB.NET code → MSIL (Intermediate Code) CLR converts MSIL → machine code
through the Just-In-Time (JIT) compiler.

(d) Security CLR enforces Code Access Security (CAS) and type-safety to ensure secure execution.

(e) Thread Management Managing threads, synchronization, and multitasking is also controlled by
CLR.

(f) Interoperability Allows .NET applications to interact with older applications such as COM
components.

■ 2. Framework Class Library (FCL / BCL) FCL is a rich collection of reusable classes, interfaces, and
namespaces.

Features of FCL: (a) Input/Output Handling (System.IO) Includes classes like File, Directory,
StreamReader, StreamWriter.

(b) Data Access (System.Data) Supports ADO.NET, SQL operations, DataSet, DataTable.

(c) Collections (System.Collections, System.Collections.Generic) Provides data structures like List,


Stack, Queue, Dictionary.

(d) Windows Forms (System.Windows.Forms) Provides controls like TextBox, Button, Label,
ComboBox, etc.

(e) Networking (System.Net) Used for sending/receiving data over networks.

FCL reduces development time because programmers don’t need to write everything from scratch.

■ 3. Common Type System (CTS) CTS ensures that all .NET languages follow a common set of rules
for declaring and using data types. This is essential for language interoperability.
Two types defined by CTS: ✔ (a) Value Types Stored in stack

Examples: Integer, Boolean, Char, Structure

Faster execution

✔ (b) Reference Types Stored in heap

Examples: String, Class, Object, Arrays

Flexible and dynamic

Purpose of CTS: Ensures all languages share the same data types

Allows one language to use code written in another

Avoids data-type conflicts

■ 4. Common Language Specification (CLS) CLS is a subset of CTS. It defines a set of rules and
restrictions that all .NET languages must follow to remain compatible with each other.

Features of CLS: Ensures code written in VB.NET can be used in C# and vice■versa

Defines standards for naming conventions, types, and methods

Example: C# supports unsigned integers (uint), but VB.NET does not → therefore, unsigned types are
not CLS■compliant.

CLS ensures smooth cross■language combination inside .NET.

■ 5. Execution Process in .NET Framework (Very important for 10 marks) Step 1: Writing Code
Developer writes code in VB.NET / C#.

Step 2: Compilation Language compiler converts the source code → MSIL + Metadata

Step 3: CLR Execution CLR loads the MSIL ↓ JIT compiler converts it to native machine code ↓ OS
executes the application

This multi-step process ensures safety, portability, and high performance.

■ 6. Diagram (Write exactly like this in exam) +-----------------------------------------------------+ | Application


Programs (VB.NET) | +-----------------------------------------------------+ ↓ Language Compilers ↓
+-----------------------------------------------------+ | MSIL Code + Metadata (Assembly) |
+-----------------------------------------------------+ ↓ Common Language Runtime (CLR) (JIT Compiler,
Security, GC, Threading) ↓ +-----------------------------------------------------+ | Framework Class Library (FCL)
| +-----------------------------------------------------+ ↓ Operating System (Windows)
■ Q2 – 10 Marks (EXAM■STYLE, SAME FORMAT AS Q1) Describe the Visual
Studio .NET IDE. Discuss Toolbox, Solution Explorer, Properties Window, Class
View, Output Window and Command Window.

Introduction Visual Studio .NET (VS.NET) is a powerful and widely used Integrated Development
Environment (IDE) developed by Microsoft for building .NET applications. It supports multiple languages
like VB.NET, C#, F#, etc., and provides all the tools required to design user interfaces, write code,
debug programs, and manage projects efficiently.

The IDE is well■organized and contains several important windows and tools that simplify the
development process.

■ Main Components of Visual Studio .NET IDE Below are the key components of the IDE explained in
detail.

■ 1. Toolbox Definition The Toolbox is a panel that contains a collection of controls and components
that can be placed on forms during application design.

Functions and Features Used mainly during GUI development.

Controls can be added to the form using drag■and■drop.

Controls are grouped into categories such as:

Common Controls (Button, Label, TextBox)

Containers (GroupBox, Panel)

Menus & Toolbars

Dialogs (OpenFileDialog, ColorDialog)

Components (Timer, ErrorProvider)

Advantages Makes form designing fast and simple.

No need to manually code the control appearance.

■ 2. Solution Explorer Definition Solution Explorer displays the project structure in a tree■view format.
It is the main navigation tool of the IDE.

What Solution Explorer Shows Project name

Forms (.vb files)

Class files

Modules

Resources (images, icons)

References
App.config file

Uses Adding or deleting files

Opening forms/classes

Managing project references

Viewing entire application structure

Solution Explorer helps developers manage multi■file applications easily.

■ 3. Properties Window Definition The Properties Window shows and allows editing of the attributes of
a selected control, component, or form.

Common Properties Name – programming name of the control

Text – displayed text

Font – style and size

BackColor / ForeColor – colors

Size, Width, Height

Enabled, Visible

Events Section There is an Events tab (lightning icon) that lists event handlers such as:

Click (for Button)

TextChanged (for TextBox)

Load (for Form)

Uses Modify control appearance

Configure behavior

Assign event handlers

■ 4. Class View Definition Class View provides a hierarchical view of all classes, methods, properties,
variables, interfaces, and namespaces used in the project.

Benefits Helps understand the overall code structure

Useful for Object■Oriented Programming

Easy navigation to methods and classes

Shows inheritance and relationships


Class View is especially helpful in large projects where many classes are involved.

■ 5. Output Window Definition The Output Window displays the messages generated during the build,
debug, or execution process.

Common Messages Shown Build success or failure

Error and warning summary

Debugging information

Loaded modules

Importance Helps in identifying code problems

Shows compiler messages

Assists during debugging sessions

■ 6. Command Window Definition The Command Window is used to execute IDE■specific commands
and perform various operations using text commands.

Uses Executing Visual Studio commands (e.g., Edit.GoTo)

Evaluating expressions during debugging

Quickly navigating files and functions

It is used mostly by advanced developers.

■ Additional IDE Components (for 10■marks completeness) Menu Bar Contains menus like File, Edit,
View, Project, Build, Debug, Tools, etc.

Tool Bar Provides quick access buttons for Save, Build, Run, Undo, Redo, etc.

Code Editor Syntax highlighting

Auto■suggestions

Error underlining

Intellisense support

Form Designer Used to design GUI applications visually using drag■and■drop.

Error List Window Displays detailed errors, warnings, and suggestions.

■ Diagram (Exam■Style) +-----------------------------------------------------+ | Visual Studio .NET IDE |


+-----------------------------------------------------+ | Menu Bar | ToolBar | Toolbox | Solution Explorer | |
Properties Window | Class View | Output Window | | Command Window | Error List | Code Editor |
+-----------------------------------------------------+ | Form Designer (GUI Development) |
+-----------------------------------------------------+
■ Q3 – 10 Marks (Full Exam■Style Answer)

Explain Data Types, Variables, Constants and Operators in VB.NET with suitable examples.

■ Introduction
VB.NET is a strongly typed programming language, which means every variable or constant must be
declared with a specific data type.
Understanding data types, variables, constants, and operators is essential for writing any VB.NET
program.
These concepts define how data is stored, accessed, and manipulated within a program.
The VB.NET language provides a rich set of built-in types and operators for performing computations
effectively.

■ 1. Data Types in VB.NET


Data types define the type of data a variable can store.
VB.NET supports a wide range of data types that fall under the Common Type System (CTS).

(a) Numeric Data Types


Data Type Size Description
Byte 1 byte 0 to 255
Short 2 bytes Integer values (−32,768 to 32,767)
Integer 4 bytes Whole numbers
Long 8 bytes Large whole numbers
Single 4 bytes Floating point (single precision)
Double 8 bytes Floating point (double precision)
Decimal 16 bytes High-precision calculations
(b) Non-Numeric Data Types
Data Type Description
Char Stores a single character
String Stores multiple characters
Boolean True/False
Date Represents date and time
Object Can store any type of data
Example
Dim age As Integer
Dim price As Double
Dim name As String
Dim isActive As Boolean
■ 2. Variables in VB.NET
Definition
A variable is a memory location used to store data that can change during program execution.

Rules for Variable Declaration


Must start with a letter

Cannot contain spaces

Should be meaningful

Syntax:
Dim variableName As DataType
Examples:
Dim studentName As String = "Ankur"
Dim marks As Integer = 85
Dim percentage As Double = 88.5
Types of Variables
Local Variables – declared inside a procedure

Module-level Variables – declared inside a module

Global Variables – declared with Public keyword

Public totalStudents As Integer


■ 3. Constants in VB.NET
Definition
A constant is a fixed value whose value cannot be changed during execution.

Syntax:
Const constantName As DataType = value
Examples:
Const PI As Double = 3.14159
Const CollegeName As String = "DBRAU"
Const MaxMarks As Integer = 100
Advantages of Constants
Improves readability

Easier to maintain

Prevents accidental modification

■ 4. Operators in VB.NET
Operators are symbols used to perform calculations or operations on variables and values.

■ (A) Arithmetic Operators


Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division (floating) a / b
\ Integer Division a \ b
Mod Remainder a Mod b
^ Exponent a ^ b
Example
Dim a As Integer = 10
Dim b As Integer = 3
Dim c As Integer = a Mod b 'Result = 1
■ (B) Relational Operators
Used to compare two values.

Operator Meaning
= Equal to
<> Not Equal to
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Example:
If marks >= 40 Then
Console.WriteLine("Pass")
End If
■ (C) Logical Operators
Operator Description
And True if both are True
Or True if any one is True
Not Reverses the condition
Example:
If age > 18 And isActive = True Then
Console.WriteLine("Eligible")
End If
■ (D) Assignment Operators
Operator Meaning
= Assigns value
+= Add and assign
-= Subtract and assign
*= Multiply and assign
x += 5 'same as x = x + 5
■ (E) String Operators
& Operator (Concatenation)
Dim fullName As String
fullName = firstName & " " & lastName
■ 5. Example Program Combining All Concepts
Module Module1
Sub Main()
'Variables
Dim name As String = "Ankur"
Dim marks As Integer = 92
Const MaxMarks As Integer = 100

'Operators
Dim percentage As Double
percentage = (marks / MaxMarks) * 100

'Output
Console.WriteLine("Name: " & name)
Console.WriteLine("Percentage: " & percentage & "%")

Console.ReadLine()
End Sub
End Module
■ Q4 – 10 Marks (Full Exam■Style Answer)

Explain Conditional Statements and Looping Constructs in VB.NET. Discuss If■Else, Select Case, For,
While, Do■While, and For Each with suitable examples.

■ Introduction
In VB.NET, control structures are used to control the flow of execution in a program.
There are two major types of control structures:

Conditional Statements – used for decision■making

Looping (Iterative) Statements – used for repeating tasks

These structures are essential for writing logical, efficient, and organized programs.

■ 1. Conditional Statements in VB.NET


Conditional statements allow the program to execute different blocks of code depending on the
evaluation of conditions.

■ A. If…Then Statement
Definition
It checks a condition and executes a block of code if the condition is true.

Syntax
If condition Then
'Statements
End If
Example
If marks >= 40 Then
Console.WriteLine("Pass")
End If
■ B. If…Else Statement
Definition
Executes one block if the condition is true, otherwise executes another block.

Example
If age >= 18 Then
Console.WriteLine("Eligible to vote")
Else
Console.WriteLine("Not eligible")
End If
■ C. If…ElseIf…Else (Multiple Conditions)
Used when multiple conditions need to be checked.

Example
If marks >= 75 Then
Console.WriteLine("Distinction")
ElseIf marks >= 60 Then
Console.WriteLine("First Division")
ElseIf marks >= 40 Then
Console.WriteLine("Pass")
Else
Console.WriteLine("Fail")
End If
■ D. Select Case Statement
Definition
An alternative to multiple If…ElseIf statements. It improves readability.

Syntax
Select Case expression
Case value1
'Statements
Case value2
'Statements
Case Else
'Default
End Select
Example
Select Case day
Case 1
Console.WriteLine("Monday")
Case 2
Console.WriteLine("Tuesday")
Case Else
Console.WriteLine("Invalid Day")
End Select
■ 2. Looping Constructs in VB.NET
Loops are used to execute a block of statements repeatedly until a specific condition is met.

■ A. For Loop
Definition
Used when the number of repetitions is known.

Syntax
For counter = start To end Step increment
'Statements
Next
Example
For i = 1 To 5
Console.WriteLine("Value of i = " & i)
Next
■ B. For Each Loop
Definition
Used to iterate through collections, arrays, or lists.

Example
Dim names() As String = {"Ankur", "Ravi", "Kanishk"}

For Each n In names


Console.WriteLine(n)
Next
■ C. While Loop
Definition
Runs as long as the condition remains true.
Syntax
While condition
'Statements
End While
Example
Dim x As Integer = 1
While x <= 5
Console.WriteLine(x)
x += 1
End While
■ D. Do…While Loop
Definition
Executes the loop body while the condition is true.

Example
Dim i As Integer = 1
Do While i <= 5
Console.WriteLine(i)
i += 1
Loop
■ E. Do…Until Loop
Definition
Runs the loop until the condition becomes true.

Example
Dim k As Integer = 1
Do Until k > 5
Console.WriteLine(k)
k += 1
Loop
■ 3. Differences Between Conditional & Looping Statements
Conditional Statements Looping Statements
Used for decision■making Used for repetition
Executes once Executes multiple times
If, Else, Select Case For, While, Do■While
■ 4. Combined Example Program
Module Module1
Sub Main()
Dim marks As Integer = 72

'Conditional Statement
If marks >= 60 Then
Console.WriteLine("First Division")
Else
Console.WriteLine("Second Division")
End If

'Looping Example
For i As Integer = 1 To 5
Console.WriteLine("Count: " & i)
Next
Console.ReadLine()
End Sub
End Module
■ Q5 – 10 Marks (Full Exam■Style Answer)

Describe Windows Form Controls in VB.NET. Explain TextBox, Label, Button, ComboBox, ListBox and
DateTimePicker with their important properties and events.

■ Introduction
Windows Forms in VB.NET provide a graphical environment for building desktop applications.
A Windows Form contains various controls which help in taking input, displaying output, selecting data,
performing actions, and interacting with users.
Common controls include TextBox, Label, Button, ComboBox, ListBox, and DateTimePicker.
Each control has its own properties, methods, and events that define how it looks and behaves.

■ 1. TextBox Control
Definition
A TextBox is used to take input from the user in the form of text.

Common Properties
Text – Gets/sets the entered text

MaxLength – Maximum characters allowed

Multiline – True/False (multiple lines allowed)

ReadOnly – Prevents editing

PasswordChar – Masks characters (for password fields)

Important Events
TextChanged – Occurs when the text is modified

KeyPress – Triggered when a key is pressed

Example
TextBox1.Text = "Enter your name"
■ 2. Label Control
Definition
Label is used to display static text or messages on a form.

Common Properties
Text – Text to be displayed

Font – Font settings

ForeColor – Text color

BackColor – Background color

AutoSize – Adjusts size automatically to fit text

Uses
Instructions, headings, messages

Displaying output
Example
Label1.Text = "Enter Name:"
■ 3. Button Control
Definition
Button is used to perform an action when clicked.

Common Properties
Text – Caption on the button

Enabled – Enable/Disable the button

BackColor / ForeColor – Colors

Image – Display an image on the button

Important Event
Click – Fired when the user clicks on the button

Example
Private Sub Button1_Click(...)
MessageBox.Show("Button clicked!")
End Sub
■ 4. ComboBox Control
Definition
ComboBox is a drop■down list that allows users to select one item from a list.

Common Properties
Items – Collection of list items

SelectedItem – Current selected item

SelectedIndex – Index of selected item

DropDownStyle – Determines editability

DropDown

DropDownList

Simple

Useful Methods
Items.Add()

Items.Remove()

Example
ComboBox1.Items.Add("BCA")
ComboBox1.Items.Add("B.Sc")
Event
SelectedIndexChanged – fired when selection changes
■ 5. ListBox Control
Definition
ListBox displays a list of items; user can select one or multiple items based on settings.

Common Properties
Items – List of items

SelectedItem – Currently selected item

SelectionMode – Single or Multi■Select

TopIndex – First visible item index

Methods
Items.Add()

Items.Clear()

Items.Remove()

Example
ListBox1.Items.Add("Monday")
ListBox1.Items.Add("Tuesday")
Event
SelectedIndexChanged – triggered when selection changes

■ 6. DateTimePicker Control
Definition
DateTimePicker allows the user to select a date, time, or both in a standardized format.

Common Properties
Value – Stores the selected date

Format – Defines display format

Long

Short

Time

Custom

MinDate / MaxDate – Sets valid date range

CustomFormat – User■defined format

Example
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd-MM-yyyy"
Events
ValueChanged – triggered when selected date changes

■ 7. General Features of Windows Form Controls


All controls inherit from System.Windows.Forms.Control

Support for events, methods, properties

Controls can be added using drag■and■drop

Provide graphical and interactive features

Support resizing, anchoring, docking, and alignment

■ Example Program Using All Controls


Private Sub Button1_Click(...)
Dim nm As String = TextBox1.Text
Dim course As String = ComboBox1.SelectedItem
Dim day As String = ListBox1.SelectedItem

MessageBox.Show("Name: " & nm &


vbCrLf & "Course: " & course &
vbCrLf & "Day: " & day &
vbCrLf & "Date: " & DateTimePicker1.Value)
End Sub
■ Q6 – 10 Marks (Full Exam■Style Answer)

Explain Built■in Dialog Boxes in VB.NET: OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog,


PrintDialog, MsgBox and InputBox with their usage.

■ Introduction
Dialog boxes in VB.NET are special windows that allow users to perform common tasks such as
selecting a file, choosing colors, fonts, saving documents, printing pages, or entering a message.
VB.NET provides several built■in dialog controls that make application development easier and more
interactive.
These dialog boxes belong to the System.Windows.Forms namespace and can be used by simply
dragging them from the Toolbox or creating them through code.

■ 1. OpenFileDialog
Definition
OpenFileDialog is used to browse and select an existing file from the system.

Common Properties
Filter – limits the file types (e.g., *.txt, *.jpg)

FileName – selected file’s path

InitialDirectory – default folder

Title – title text of the dialog

Important Method
ShowDialog() – opens the dialog

Example
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
End If
Usage
Used in applications requiring file selection such as reading documents, opening images, or loading
records.

■ 2. SaveFileDialog
Definition
SaveFileDialog is used to save a file to a user■selected location.

Common Properties
Filter – specifies file extensions

FileName – default file name

OverwritePrompt – warns before overwriting

InitialDirectory – starting folder

Example
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
File.WriteAllText(SaveFileDialog1.FileName, TextBox1.Text)
End If
Usage
Used in text editors, report writers, image editors, and document■saving applications.

■ 3. FontDialog
Definition
FontDialog allows users to select a font style, size, and various attributes for text.

Common Properties
Font – selected font

ShowColor – allows color selection

Color – selected color

Example
If FontDialog1.ShowDialog() = DialogResult.OK Then
TextBox1.Font = FontDialog1.Font
End If
Usage
Used in word processors, text editors, and customizable UI applications.

■ 4. ColorDialog
Definition
ColorDialog enables the user to select a color from the standard color palette.

Common Properties
Color – selected color

AllowFullOpen – shows full palette

FullOpen – opens palette automatically

Example
If ColorDialog1.ShowDialog() = DialogResult.OK Then
TextBox1.BackColor = ColorDialog1.Color
End If
Usage
Used in design tools, drawing programs, and themes.

■ 5. PrintDialog
Definition
PrintDialog is used to configure printing tasks.

Common Properties
PrinterSettings – available printers

AllowPrintToFile

AllowSelection

AllowSomePages
Example
If PrintDialog1.ShowDialog() = DialogResult.OK Then
PrintDocument1.Print()
End If
Usage
Used in report generation, invoice printing, and document applications.

■ 6. MsgBox (Message Box)


Definition
MsgBox is used to display a message or prompt the user for a decision.

Syntax
MsgBox(prompt, buttons, title)
Examples
MsgBox("Operation Successful")
Dim result = MsgBox("Do you want to exit?", MsgBoxStyle.YesNo)
Usage
Used for alerts, confirmations, warnings, and simple notifications.

■ 7. InputBox
Definition
InputBox allows users to enter a single line of text in a small dialog box.

Syntax
InputBox(prompt, title)
Example
Dim userName As String
userName = InputBox("Enter your name:", "User Input")
Usage
Used for small inputs such as names, numbers, or quick entries without creating a full form.

■ Advantages of Built■in Dialog Boxes


Eliminates need to design custom forms

Saves development time

Consistent Windows interface

Easy to implement and use

Provides user■friendly interaction

■ Diagram (Exam■Style Representation)


Built■in Dialog Boxes in VB.NET
------------------------------------------
| OpenFileDialog | SaveFileDialog |
| FontDialog | ColorDialog |
| PrintDialog | MsgBox |
| InputBox | |
------------------------------------------
Each dialog performs a specific user task
such as file selection, saving, printing,
choosing fonts, colors, and taking input.
■ Q7 – 10 Marks (Full Exam■Style Answer)

What are Functions and Procedures in VB.NET? Explain the differences between them and write
suitable examples. Also explain User■Defined Functions.

■ Introduction
In VB.NET, procedures and functions are blocks of code designed to perform specific tasks.
They help in code reusability, modular programming, readability, and error reduction.
Both procedures and functions may accept input values called parameters, but functions return a value
whereas procedures do not.

■ 1. Procedures in VB.NET
Definition
A Procedure is a block of statements that performs a task but does not return a value.

There are two types of procedures:

Sub Procedures

Event Procedures

■ A. Sub Procedure
Syntax
Sub ProcedureName(parameters)
'Statements
End Sub
Example
Sub DisplayMessage()
Console.WriteLine("Welcome to VB.NET")
End Sub
Sub Procedure with Parameters
Sub Add(a As Integer, b As Integer)
Console.WriteLine("Sum = " & (a + b))
End Sub
■ 2. Functions in VB.NET
Definition
A Function is a block of code that returns a value after performing a task.

Syntax
Function FunctionName(parameters) As DataType
'Statements
Return value
End Function
Example
Function Square(num As Integer) As Integer
Return num * num
End Function
Function with multiple parameters
Function CalculateTotal(marks1 As Integer, marks2 As Integer) As Integer
Return marks1 + marks2
End Function
■ 3. User■Defined Functions
Definition
User■Defined Functions are functions created by the programmer to solve specific problems that are
not available in built■in libraries.

Characteristics
Custom logic designed by the user

Improve reusability

Make code modular

Can return any data type

Example of User■Defined Function


Function GetGrade(marks As Integer) As String
If marks >= 75 Then
Return "Distinction"
ElseIf marks >= 60 Then
Return "First Division"
ElseIf marks >= 40 Then
Return "Pass"
Else
Return "Fail"
End If
End Function
■ 4. Calling Procedures and Functions
Calling a Procedure
Call DisplayMessage()
Calling a Function
Dim result As Integer
result = Square(5)
Console.WriteLine("Square: " & result)
■ 5. Differences Between Function and Procedure
Feature Function Procedure
Returns Value Yes, must return a value No, does not return a value
Syntax Uses Function ... End Function Uses Sub ... End Sub
Usage Used for calculations, and returning results Used for tasks or actions
Called as Part of expressions Separate statement
Return Keyword Mandatory Not used
■ 6. Combined Example Program
Module Module1

Sub Main()
'Calling Procedure
GreetUser("Ankur")

'Calling Function
Dim total As Integer = AddNumbers(10, 20)
Console.WriteLine("Total = " & total)

Console.ReadLine()
End Sub
'Procedure
Sub GreetUser(name As String)
Console.WriteLine("Hello " & name)
End Sub

'User-defined Function
Function AddNumbers(a As Integer, b As Integer) As Integer
Return a + b
End Function

End Module
■ Q8 – 10 Marks (Full Exam■Style Answer)

Explain Object-Oriented Programming in VB.NET. Describe Class, Object, Fields, Methods,


Constructors, Destructors and Events with suitable examples.

■ Introduction
Object-Oriented Programming (OOP) is a programming paradigm based on the concepts of objects and
classes.
VB.NET fully supports OOP principles such as:

Encapsulation

Inheritance

Polymorphism

Abstraction

OOP helps in building modular, reusable, secure, and well■organized applications.

■ 1. Class in VB.NET
Definition
A Class is a blueprint or template for creating objects.
It defines the structure of data (fields) and the behavior (methods) of an object.

Syntax
Public Class Student
'Fields and Methods
End Class
Example
Public Class Student
Public name As String
Public age As Integer
End Class
Classes provide a way to model real■world entities in programming.

■ 2. Object in VB.NET
Definition
An Object is an instance of a class.
It represents a real entity created from the class blueprint.

Syntax
Dim s As New Student()
Example
Dim s1 As New Student()
s1.name = "Ankur"
s1.age = 20
Objects store data and perform actions using methods.

■ 3. Fields (Data Members)


Definition
Fields are variables declared inside a class.
They store the state (data) of an object.
Example
Public Class Car
Public brand As String
Public year As Integer
End Class
Fields represent the attributes of an object.

■ 4. Methods (Member Functions)


Definition
Methods are functions declared inside a class.
They define the behavior or operations performed by the object.

Example
Public Class Car
Public Sub DisplayInfo()
Console.WriteLine("Car Information")
End Sub
End Class
Methods allow objects to perform actions.

■ 5. Constructors
Definition
A constructor is a special method that is automatically called when an object is created.
It initializes fields and allocates memory.

Syntax
Public Sub New()
'Initialization Code
End Sub
Example
Public Class Student
Public name As String
Public Sub New(n As String)
name = n
End Sub
End Class
Calling
Dim s As New Student("Ankur")
Constructors improve initialization and setup of objects.

■ 6. Destructors (Finalize Method)


Definition
A destructor is used to perform cleanup operations before an object is destroyed.

Example
Protected Overrides Sub Finalize()
Console.WriteLine("Object destroyed")
End Sub
Destructors are rarely needed in .NET because the Garbage Collector automatically manages memory.

■ 7. Events in VB.NET
Definition
Events are actions or occurrences recognized by a program.
Events are mostly triggered by user actions (mouse click, key press) or system actions.

Example
Public Class ButtonTest
Public Sub New()
End Sub

Private Sub Button1_Click(...) Handles Button1.Click


MessageBox.Show("Button Clicked!")
End Sub
End Class
Events in VB.NET use delegates internally and allow development of interactive applications.

■ 8. Combined Example (Class + Object + Methods + Constructor + Event)


Public Class Student
Public name As String
Public age As Integer

'Constructor
Public Sub New(n As String, a As Integer)
name = n
age = a
End Sub

'Method
Public Sub Display()
Console.WriteLine("Name: " & name)
Console.WriteLine("Age: " & age)
End Sub
End Class

'Main Program
Module Module1
Sub Main()
Dim s As New Student("Ankur", 21)
s.Display()
End Sub
End Module
■ 9. Advantages of OOP in VB.NET
Code Reusability

Better Security (Encapsulation)

Easy Maintenance

Real■world Modeling

Polymorphism allows flexibility

Inheritance reduces redundancy


■ Q9 – 10 Marks (Full Exam■Style Answer)

Discuss File Handling in VB.NET. Explain FileStream, StreamReader and StreamWriter with code to
read and write text files.

■ Introduction
File handling in VB.NET allows programs to create, read, write, and modify files stored on the system.
The .NET Framework provides powerful classes in the System.IO namespace that make file operations
easy and efficient.

Three important file■handling classes are:

FileStream

StreamReader

StreamWriter

These classes help in processing text files, binary files, logs, reports, and configuration files.

■ 1. FileStream Class
Definition
FileStream is used to read from and write to files at a lower level.
It works with both text files and binary files.

Namespace
Imports System.IO
Constructor Syntax
Dim fs As New FileStream("filename.txt", FileMode.OpenOrCreate, FileAccess.Write)
Common FileMode Options
FileMode Description
Open Opens existing file
Create Creates a new file
Append Opens a file and writes at end
OpenOrCreate Opens if exists, else creates
Common FileAccess Options
FileAccess Meaning
Read Only read access
Write Only write access
ReadWrite Both read/write
Example: Writing Using FileStream
Dim fs As New FileStream("data.txt", FileMode.Create, FileAccess.Write)
Dim info As Byte() = System.Text.Encoding.ASCII.GetBytes("Hello VB.NET")
fs.Write(info, 0, info.Length)
fs.Close()
Example: Reading Using FileStream
Dim fs As New FileStream("data.txt", FileMode.Open, FileAccess.Read)
Dim b(fs.Length - 1) As Byte
fs.Read(b, 0, b.Length)
Console.WriteLine(System.Text.Encoding.ASCII.GetString(b))
fs.Close()
■ 2. StreamReader Class
Definition
StreamReader is used to read text files line by line or character by character.
It is easier to use than FileStream for plain text files.

Syntax
Dim sr As New StreamReader("file.txt")
Common Methods
Method Description
ReadLine() Reads a single line
ReadToEnd() Reads entire file
Read() Reads a single character
Close() Closes the stream
Example: Read Text File
Dim sr As New StreamReader("data.txt")
Dim content As String = sr.ReadToEnd()
Console.WriteLine(content)
sr.Close()
■ 3. StreamWriter Class
Definition
StreamWriter is used to write text into a file.
If the file does not exist, StreamWriter can create it automatically.

Syntax
Dim sw As New StreamWriter("file.txt")
Common Methods
Method Description
Write() Writes text without newline
WriteLine() Writes text with newline
Close() Closes the stream
Example: Write Text File
Dim sw As New StreamWriter("data.txt")
sw.WriteLine("Welcome to VB.NET")
sw.WriteLine("This is file handling example.")
sw.Close()
■ 4. Combined Program (Create + Write + Read File)
Imports System.IO

Module Module1
Sub Main()

'Writing to file
Dim sw As New StreamWriter("testfile.txt")
sw.WriteLine("This is a VB.NET file handling example.")
sw.WriteLine("File handling is easy using StreamWriter and StreamReader.")
sw.Close()

'Reading from file


Dim sr As New StreamReader("testfile.txt")
Dim data As String = sr.ReadToEnd()
Console.WriteLine("File Content:")
Console.WriteLine(data)
sr.Close()
Console.ReadLine()
End Sub
End Module
■ 5. Advantages of File Handling in VB.NET
Stores data permanently

Useful for configuration, records, logs, and reports

Easy read/write operations

Supports both text and binary files

Very powerful System.IO classes

■ Diagram (Exam■Style)
System.IO Namespace
-------------------------------------
| FileStream | StreamReader | StreamWriter |
-------------------------------------
|||
Binary Read Text Write Text
Files Files Files
■ Q10 – 10 Marks (Full Exam■Style Answer)

What is ADO.NET? Explain Connected and Disconnected Architecture. Describe DataAdapter,


DataSet, DataTable and basic SQL operations.

■ Introduction
ADO.NET (ActiveX Data Objects .NET) is a data access technology provided by the .NET Framework
for interacting with relational databases such as SQL Server, Oracle, MS Access, MySQL, etc.
It provides a fast, secure, and scalable way to retrieve, manipulate, and update data using two main
approaches:

Connected Architecture

Disconnected Architecture

ADO.NET classes are available under the System.Data namespace and support XML, datasets, data
readers, commands, and adapters.

■ 1. Features of ADO.NET
Supports multiple data providers

Works in connected and disconnected modes

XML integration

High performance and scalability

Secure communication with databases

Provider■specific classes (SqlConnection, OleDbConnection, etc.)

■ 2. Connected Architecture
Definition
Connected architecture requires an active, continuous connection between the application and the
database while fetching data.

Key Object: DataReader


A DataReader retrieves data from the database in a fast, forward■only, read■only manner.

Classes Used
SqlConnection

SqlCommand

SqlDataReader

Example (Connected Mode)


Dim con As New SqlConnection("connection_string")
Dim cmd As New SqlCommand("SELECT * FROM Students", con)

con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Console.WriteLine(dr("Name"))
End While

con.Close()
Advantages
Fast and efficient

Best for read■only operations

Disadvantages
Connection must remain open

Not suitable for offline access

■ 3. Disconnected Architecture
Definition
Disconnected architecture allows data to be retrieved and stored in memory without maintaining a
continuous connection to the database.

The key component is the DataSet, which stores multiple tables in memory.

Classes Used
DataSet

DataTable

DataAdapter

How It Works
Connection opens

DataAdapter fills DataSet

Connection closes

Application works with DataSet offline

DataAdapter updates database when needed

This architecture is ideal for distributed applications.

■ 4. DataAdapter
Definition
A DataAdapter acts as a bridge between the database and the DataSet.
It fills the DataSet and sends updates back to the database.

Commands used by DataAdapter


SelectCommand

InsertCommand
UpdateCommand

DeleteCommand

Example
Dim da As New SqlDataAdapter("SELECT * FROM Students", con)
Dim ds As New DataSet()
da.Fill(ds, "Students")
■ 5. DataSet
Definition
A DataSet is a memory■resident, disconnected data storage container.
It can hold multiple tables, relations, and constraints.

Features
Works without continuous connection

XML supported

Contains DataTables and DataRelations

Example
Dim ds As New DataSet()
da.Fill(ds)
Console.WriteLine(ds.Tables(0).Rows.Count)
■ 6. DataTable
Definition
A DataTable represents a single table inside a DataSet.

Components
Columns (structure)

Rows (data)

Constraints

Example
Dim dt As DataTable = ds.Tables("Students")

For Each row As DataRow In dt.Rows


Console.WriteLine(row("Name"))
Next
■ 7. Basic SQL Operations Using ADO.NET
(A) Insert Operation
Dim cmd As New SqlCommand("INSERT INTO Students(Name, Age) VALUES('Ankur', 22)", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
(B) Update Operation
Dim cmd As New SqlCommand("UPDATE Students SET Age=23 WHERE Name='Ankur'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
(C) Delete Operation
Dim cmd As New SqlCommand("DELETE FROM Students WHERE Name='Ankur'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
(D) Select Operation
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
■ 8. Difference Between Connected vs Disconnected Architecture
Feature Connected Disconnected
Requires continuous connection Yes No
Main Object DataReader DataSet / DataTable
Speed Very fast Moderate
Editing Data Not supported Fully supported
Best Use Read-only operations Offline and batch operations

You might also like