0% found this document useful (0 votes)
9 views59 pages

Application Development On

Uploaded by

kumar.nivas7573
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)
9 views59 pages

Application Development On

Uploaded by

kumar.nivas7573
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
You are on page 1/ 59

GOODWILL CHRISTIAN COLLEGE FOR WOMEN

C# AND DOT NET


FRAMEWORK
UNIT 4 APPLICATION DEVELOPMENT ON .NET
KAVITHA RAJALAKSHMI D
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

C# .NET: BUILDING WINDOWS APPLICATIONS


A windows form application is an application, which is designed to run on a computer. It will
not run on web browser because then it becomes a web application.
This Tutorial will focus on how we can create Windows-based applications. We will also learn
some basics on how to work with the various elements of C# Windows application.

Windows Forms Basics


A Windows forms application is one that runs on the desktop computer. A Windows forms
application will normally have a collection of controls such as labels, textboxes, list boxes, etc.
Below is an example of a simple Windows form application C#. It shows a simple Login
screen, which is accessible by the user. The user will enter the required credentials and then
will click the Login button to proceed.

So an example of the controls available in the above application


1. This is a collection of label controls which are normally used to describe adjacent
controls. So in our case, we have 2 textboxes, and the labels are used to tell the user that
one textbox is for entering the user name and the other for the password.
2. The 2 textboxes are used to hold the username and password which will be entered by
the user.
3. Finally, we have the button control. The button control will normally have some code
attached to perform a certain set of actions. So for example in the above case, we could
have the button perform an action of validating the user name and password which is
entered by the user.

C# Hello World
Now let’s look at an example of how we can implement a simple ‘hello world’ application in
Visual Studio. For this, we would need to implement the below-mentioned steps

Step 1) The first step involves the creation of a new project in Visual Studio. After launching
Visual Studio, you need to choose the menu option New->Project.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 1


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Step 2) The next step is to choose the project type as a Windows Forms application. Here we
also need to mention the name and location of our project.

1. In the project dialog box, we can see various options for creating different types of
projects in Visual Studio. Click the Windows option on the left-hand side.
2. When we click the Windows options in the previous step, we will be able to see an
option for Windows Forms Application. Click this option.
3. We will give a name for the application. In our case, it is DemoApplication. We will
also provide a location to store our application.
4. Finally, we click the ‘OK’ button to let Visual Studio create our project.
If the above steps are followed, you will get the below output in Visual Studio.

Output:-

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 2


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

You will see a Form Designer displayed in Visual Studio. It’s in this Form Designer that you
will start building your Windows Forms application.

In the Solution Explorer, you will also be able to see the DemoApplication Solution. This
solution will contain the below 2 project files
1. A Form application called Forms1.cs. This file will contain all of the code for the
Windows Form application.
2. The Main program called Program.cs is default code file which is created when a new
application is created in Visual Studio. This code will contain the startup code for the
application as a whole.
On the left-hand side of Visual Studio, you will also see a ToolBox. The toolbox contains all
the controls which can be added to a Windows Forms. Controls like a text box or a label are
just some of the controls which can be added to a Windows Forms.
Below is a screenshot of how the Toolbox looks like.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 3


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Step 3) In this step, we will now add a label to the Form which will display “Hello World.”
From the toolbox, you will need to choose the Label control and simply drag it onto the Form.

Once you drag the label to the form, you can see the label embedded on the form as shown
below.

Step 4) The next step is to go to the properties of the control and Change the text to ‘Hello
World’.
To go to the properties of a control, you need to right-click the control and choose the
Properties menu option

 The properties panel also shows up in Visual Studio. So for the label control, in the
properties control, go to the Text section and enter “Hello World”.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 4


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

 Each Control has a set of properties which describe the control.

If you follow all of the above steps and run your program in Visual Studio, you will get the
following output

Output:-

In the output, you can see that the Windows Form is displayed. You can also see ‘Hello World’
is displayed on the form.

Adding Controls to a form


We had already seen how to add a control to a form when we added the label control in the
earlier section to display “Hello World.”
Let’s look at the other controls available for Windows forms and see some of their common
properties.
In our Windows form application in C# examples, we will create one form which will have the
following functionality.

1. The ability for the user to enter name and address.


2. An option to choose the city in which the user resides in
3. The ability for the user to enter an option for the gender.
4. An option to choose a course which the user wants to learn. There will make choices for
both C# and ASP.Net
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 5
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

So let’s look at each control in detail and add them to build the form with the above-mentioned
functionality.

GROUP BOX
A group box is used for logical grouping controls into a section. Let’s take an example if you
had a collection of controls for entering details such as name and address of a person. Ideally,
these are details of a person, so you would want to have these details in a separate section on
the Form. For this purpose, you can have a group box. Let’s see how we can implement this
with an example shown below
Step 1) The first step is to drag the Groupbox control onto the Windows Form from the
toolbox as shown below

Step 2) Once the groupbox has been added, go to the properties window by clicking on the
groupbox control. In the properties window, go to the Text property and change it to “User
Details”.

Once you make the above changes, you will see the following output

Output:-

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 6


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

In the output, you can clearly see that the Groupbox was added to the form. You can also see
that the text of the groupbox was changed to “User Details.”

LABEL CONTROL
Next comes the Label Control. The label control is used to display a text or a message to the
user on the form. The label control is normally used along with other controls. Common
examples are wherein a label is added along with the textbox control.
The label indicates to the user on what is expected to fill up in the textbox. Let’s see how we
can implement this with an example shown below. We will add 2 labels, one which will be
called ‘name’ and the other called ‘address.’ They will be used in conjunction with the textbox
controls which will be added in the later section.
Step 1) The first step is to drag the label control on to the Windows Form from the toolbox as
shown below. Make sure you drag the label control 2 times so that you can have one for the
‘name’ and the other for the ‘address’.

Step 2) Once the label has been added, go to the properties window by clicking on the label
control. In the properties window, go to the Text property of each label control.

Once you make the above changes, you will see the following output

Output:-

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 7


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

You can see the label controls added to the form.

TEXTBOX
A textbox is used for allowing a user to enter some text on the Windows application in C#.
Let’s see how we can implement this with an example shown below. We will add 2 textboxes
to the form, one for the Name and the other for the address to be entered for the user

Step 1) The first step is to drag the textbox control onto the Windows Form from the toolbox
as shown below

Step 2) Once the text boxes have been added, go to the properties window by clicking on the
textbox control. In the properties window, go to the Name property and add a meaningful name
to each textbox. For example, name the textbox for the user as txtName and that for the address
as txtAddress. A naming convention and standard should be made for controls because it
becomes easier to add extra functionality to these controls, which we will see later on.

Once you make the above changes, you will see the following output

Output:-

In the output, you can clearly see that the Textboxes was added to the form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 8


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

LIST BOX
A Listbox is used to showcase a list of items on the Windows form. Let’s see how we can
implement this with an example shown below. We will add a list box to the form to store some
city locations.
Step 1) The first step is to drag the list box control onto the Windows Form from the toolbox
as shown below

Step 2) Once the list box has been added, go to the properties window by clicking on the list
box control.

1. First, change the property of the Listbox box control, in our case, we have changed this
to lstCity
2. Click on the Items property. This will allow you to add different items which can show
up in the list box. In our case, we have selected items “collection”.

3. In the String Collection Editor, which pops up, enter the city names. In our case, we
have entered “Mumbai”, “Bangalore” and “Hyderabad”.
4. Finally, click on the ‘OK’ button.
Once you make the above changes, you will see the following output

Output:-

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 9


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

In the output, you can see that the Listbox was added to the form. You can also see that the list
box has been populated with the city values.

RADIOBUTTON
A Radiobutton is used to showcase a list of items out of which the user can choose one. Let’s
see how we can implement this with an example shown below. We will add a radio button for a
male/female option.
Step 1) The first step is to drag the ‘radiobutton’ control onto the Windows Form from the
toolbox as shown below.

Step 2) Once the Radiobutton has been added, go to the properties window by clicking on the
Radiobutton control.

1. First, you need to change the text property of both Radio controls. Go the properties
windows and change the text to a male of one radiobutton and the text of the other to
female.

2. Similarly, change the name property of both Radio controls. Go the properties windows
and change the name to ‘rdMale’ of one radiobutton and to ‘rdfemale’ for the other one.
One you make the above changes, you will see the following output

Output:-

You will see the Radio buttons added to the Windows form.

CHECKBOX
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 10
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

A checkbox is used to provide a list of options in which the user can choose multiple choices.
Let’s see how we can implement this with an example shown below. We will add 2 checkboxes
to our Windows forms. These checkboxes will provide an option to the user on whether they
want to learn C# or ASP.Net.

Step 1) The first step is to drag the checkbox control onto the Windows Form from the toolbox
as shown below

Step 2) Once the checkbox has been added, go to the properties window by clicking on the
Checkbox control.

In the properties window,


1. First, you need to change the text property of both checkbox controls. Go the properties
windows and change the text to C# and ASP.Net.
2. Similarly, change the name property of both Radio controls. Go the properties windows
and change the name to chkC of one checkbox and to chkASP for the other one.
Once you make the above changes, you will see the following output

Output:-

BUTTON

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 11


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

A button is used to allow the user to click on a button which would then start the processing of
the form. Let’s see how we can implement this with an example shown below. We will add a
simple button called ‘Submit’ which will be used to submit all the information on the form.
Step 1) The first step is to drag the button control onto the Windows Form from the toolbox as
shown below

Step 2) Once the Button has been added, go to the properties window by clicking on the Button
control.

1. First, you need to change the text property of the button control. Go the properties
windows and change the text to ‘submit’.
2. Similarly, change the name property of the control. Go the properties windows and
change the name to ‘btnSubmit’.
Once you make the above changes, you will see the following output

Output:-

Congrats, you now have your first basic Windows Form in place. Let’s now go to the next
topic to see how we can do Event handling for Controls.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 12


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

C# EVENT HANDLING FOR CONTROLS


When working with windows form, you can add events to controls. An event is something that
happens when an action is performed. Probably the most common action is the clicking of a
button on a form. In C# Windows Forms, you can add code which can be used to perform
certain actions when a button is pressed on the form.
Normally when a button is pressed on a form, it means that some processing should take place.
Let’s take a look at one of the event and how it can be handled before we go to the button event
scenario.
The below example will showcase an event for the Listbox control. So whenever an item is
selected in the listbox control, a message box should pop up which shows the item selected.
Let’s perform the following steps to achieve this.
Step 1) Double click on the Listbox in the form designer. By doing this, Visual Studio will
automatically open up the code file for the form. And it will automatically add an event method
to the code. This event method will be triggered, whenever any item in the listbox is selected.

Above is the snippet of code which is automatically added by Visual Studio, when you double-
click the List box control on the form. Now let’s add the below section of code to this snippet
of code, to add the required functionality to the listbox event.

1. This is the event handler method which is automatically created by Visual Studio when
you double-click the List box control. You don’t need to worry about the complexity of
the method name or the parameters passed to the method.
2. Here we are getting the SelectedItem through the lstCity.SelectedItem property.
Remember that lstCity is the name of our Listbox control. We then use the GetItemText
method to get the actual value of the selected item. We then assign this value to the text
variable.
3. Finally, we use the MessageBox method to display the text variable value to the user.
One you make the above changes, and run the program in Visual Studio you will see the
following output

Output:-
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 13
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

From the output, you can see that when any item from the list box is selected, a message box
will pops up. This will show the selected item from the listbox.
Now let’s look at the final control which is the button click Method. Again this follows the
same philosophy. Just double click the button in the Forms Designer and it will automatically
add the method for the button event handler. Then you just need to add the below code.

1. This is the event handler method which is automatically created by Visual Studio when
you double click the button control. You don’t need to worry on the complexity of the
method name or the parameters passed to the method.
2. Here we are getting values entered in the name and address textbox. The values can be
taken from the text property of the textbox. We then assign the values to 2 variables,
name, and address accordingly.
3. Finally, we use the MessageBox method to display the name and address values to the
user.
One you make the above changes, and run the program in Visual Studio you will see the
following output

Output:-

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 14


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

1. First, enter a value in the name and address field.


2. Then click on the Submit button
Once you click the Submit button, a message box will pop, and it will correctly show you what
you entered in the user details section.

TREE AND PICTUREBOX CONTROL


There are 2 further controls we can look at, one is the ‘Tree Control’ and the other is the
‘Image control’. Let’s look at examples of how we can implement these controls

Tree Control
– The tree control is used to list down items in a tree like fashion. Probably the best example is
when we see the Windows Explorer itself. The folder structure in Windows Explorer is like a
tree-like structure.
Let’s see how we can implement this with an example shown below.
Step 1) The first step is to drag the Tree control onto the Windows Form from the toolbox as
shown below

Step 2) The next step is to start adding nodes to the tree collection so that it can come up in the
tree accordingly. First, let’s follow the below sub-steps to add a root node to the tree collection.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 15


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

1. Go to the properties toolbox for the tree view control. Click on the Node’s property.
This will bring up the TreeNode Editor

2. In the TreeNode Editor click on the Add Root button to add a root node to the tree
collection.
3. Next, change the text of the Root node and provide the text as Root and click ‘OK’
button. This will add Root node.
Step 3) The next step is to start adding the child nodes to the tree collection. Let’s follow the
below sub-steps to add child root node to the tree collection.

1. First, click on the Add child button. This will allow you to add child nodes to the Tree
collection.
2. For each child node, change the text property. Keep on repeating the previous step and
this step and add 2 additional nodes. In the end, you will have 3 nodes as shown above,
with the text as Label, Button, and Checkbox respectively.
3. Click on the OK button

Once you have made the above changes, you will see the following output.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 16


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Output:-

You will be able to see the Tree view added to the form. When you run the Windows form
application, you can expand the root node and see the child nodes in the list.

PictureBox Control
This control is used to add images to the Winforms C#. Let’s see how we can implement this
with an example shown below.
Step 1) The first step is to drag the PictureBox control onto the C# Windows Form from the
toolbox as shown below

Step 2) The next step is to actually attach an image to the picture box control. This can be done
by following the below steps.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 17


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

1. First, click on the Image property for the PictureBox control. A new window will pops
out.

2. In this window, click on the Import button. This will be used to attach an image to the
picturebox control.
3. A dialog box will pop up in which you will be able to choose the image to attach the
picturebox
4. Click on the OK button
One you make the above changes, you will see the following output

Output:-

From the output, you can see that an image is displayed on the form.

VB.NET FORM CONTROLS


A Form is used in VB.NET to create a form-based or window-based application. Using the
form, we can build a attractive user interface. It is like a container for holding different control
that allows the user to interact with an application. The controls are an object in a form such
as buttons, Textboxes, Textarea, labels, etc. to perform some action. However, we can add any
control to the runtime by creating an instance of it.
A Form uses a System.Windows.Form namespace, and it has a wide family of controls that
add both forms and functions in a Window-based user interface.

VB.NET Form Properties


The following are the most important list of properties related to a form. And these properties
can be set or read while the application is being executed.

Properties Description

BackColor It is used to set the background color for the form.

BackgroundImage It is used to set the background image of the form.

Cursor It is used to set the cursor image when it hovers over the form.

Using the AllowDrop control in a form, it allows whether to drag


AllowDrop
and drop on the form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 18


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Font It is used to get or set the font used in a form.

Locked It determines whether the form is locked or not.

FormBorderStyle It is used to set or get border style in a form.

Text It is used to set the title for a form window.

MinimizeBox It is used to display the minimum option on the title


MinimizeBox
bar of the form.

It is used to authenticate whether a form is a container of a Multiple


IsMDIChild
Document Interface (MDI) child form.

Autoscroll It allows whether to enable auto-scrolling in a form.

MaximizeBox It is used to display the maximum option on the title bar of the form.

MaximumSize It is used to set the maximum height and width of the form.

Language It is used to specifies the localized language in a form.

AcceptButton It is used to set the form button if the enter key is pressed.

Top, Left It is used to set the top-left corner coordinates of the form in pixel.

Name It is used to define the name of the form.

MinimumSize It is used to set the minimum height and width of the form.

It uses the True or False value to enable mouse or keyboard events


Enabled
in the form.

It uses a Boolean value that represents whether you want to put the
TopMost
window form on top of the other form. By default, it is False.

Form Events
The following are the most important list of events related to a form.

Events Description

An activated event is found when the user or program activates the


Activated
form.

Click A click event is active when the form is clicked.

Closed A closed event is found before closing the form.

Closing It exists when a form is closing.

DoubleClick
DoubleClick The DoubleClick event is activated when a user double clicks on
the form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 19


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

A DragDrop event is activated when a drag and drop operation is


DragDrop
performed.

A MouseDown event is activated when the mouse pointer is on the


MouseDown
form, and the mouse button is pressed.

A GotFocus event is activated when the form control receives a


GotFocus
focus.

HelpButtonClicked It is activated when a user clicked on the help button.

A KeyDown event is activated when a key is pressed while


KeyDown
focussing on the form.

A KeyUp event is activated when a key is released while focusing


KeyUp
on the form.

Load The load event is used to load a form before it is first displayed.

LostFocus It is activated when the form loses focus.

A MouseEnter event is activated when the mouse pointer enters the


MouseEnter
form.

A MouseHover event is activated when the mouse pointer put on


MouseHover
the form.

A MouseLeave event is activated when the mouse pointer leaves


MouseLeave
the form surface.

Shown It is activated whenever the form is displayed for the first time.

A Scroll event is activated when a form is scrolled through a user


Scroll
or code.

Resize A Resize event is activated when a form is resized.

Move A Move event is activated when a form is moved.

For creating a Windows Forms application in VB.NET, we need to follow the following steps
in Microsoft Visual Studio.
1. GoTo File Menu.
2. Click on New Project.
3. Click on Windows Forms App or Application

And finally, click on the 'Create' button to create your project, and then, it displays the
following window form with a name Form1.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 20


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Now create a simple program of Windows form control in VB.NET.

Form1.vb

Public Class Form1


' Create nameStr and num variables
Dim nameStr As String
Dim num As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Loa
End Sub

' It is Label1
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
' It is TextBox1 for inserting the value.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBo
x1.TextChanged
End Sub
' It is Label2
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
End Sub

' It is a Button1 for transferring the control.


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
nameStr = TextBox1.Text
num = TextBox2.Text
Label3.Text = "You have entered the Name " & nameStr + " Number " & num

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 21


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

End Sub
' It is TextBox2 for inserting the value.
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBo
x2.TextChanged
End Sub
' It is label3
Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click

End Sub
End Class

Output:

After filling all the details, click on the Submit button. After that, it shows the following

VB.NET TIMER CONTROL


The timer control is a looping control used to repeat any task in a given time interval. It is an
important control used in Client-side and Server-side programming, also in Windows Services.
Furthermore, if we want to execute an application after a specific amount of time, we can use
the Timer Control. Once the timer is enabled, it generates a tick event handler to perform any

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 22


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

defined task in its time interval property. It starts when the start() method of timer control is
called, and it repeats the defined task continuously until the timer stops.

Let's create a Timer control in the VB.NET Windows form by using the following steps.
Step 1: Drag and drop the Timer control onto the window form, as shown below.

Step 2: Once the Timer is added to the form, we can set various properties of the Timer by
clicking on the Timer control.

Timer Control Properties


There are following properties of the VB.NET Timer control.

Properties Description

Name The Name property is used to set the name of the control.

The Enables property is used to enable or disable the timer control. By


Enabled
default, it is True.

An Interval property is used to set or obtain the iteration interval in


Interval milliseconds to raise the timer control's elapsed event. According to the
interval, a timer repeats the task.

The AutoReset property is used to obtain or set a Boolean value that


AutoReset
determines whether the timer raises the elapsed event only once.

Events property are used to get the list of event handler that is associated
Events
with Event Component.

It is used to get a value that represents whether the component can raise
CanRaiseEvents
an event.

Events of Timer Control

Events Description

Disposed When control or component is terminated by calling the Dispose method, a


Dispose event occurs.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 23


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Elapsed When the interval elapses in timer control, the Elapsed event has occurred.

Tick A tick event is used to repeat the task according to the time set in the Interval
property. It is the default event of a timer control that repeats the task between the
Start() and Stop() methods.

Methods of Timer Control

Methods Description

The BeginInt() method is used to start run time initialization of a timer


BeginInt()
control used on a form or by another component.

The Dispose() method is used to free all resources used by the Timer
Dispose()
Control or component.

Dispose(Boolean) It is used to release all resources used by the current Timer control.

The Close() method is used to release the resource used by the Timer
Close()
Control.

The Start() method is used to begin the Timer control's elapsed event by
Start()
setting the Enabled property to true.

The EndInt() method is used to end the run time initialization of timer
EndInt()
control that is used on a form or by another component.

The Stop() method is used to stop the timer control's elapsed event by
Stop()
setting Enabled property to false.

Let's create a simple program to understand the use of Timer Control in the VB.NET Windows
Forms.

TimerProgram.vb
Public Class TimerProgram
Private Sub TimerProgram_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "javatpooint.com" 'Set the title for a Windows Form
Label1.Text = "WELCOME TO JAVATPOINT.COM"
TextBox1.Text = 1
Timer1.Enabled = True
Button1.Text = "Start"
Button1.BackColor = Color.Green
Button1.ForeColor = Color.White
Button2.Text = "Stop"
Button2.BackColor = Color.Red
Button2.ForeColor = Color.White
Timer1.Start()
Timer1.Interval = 600 'set the time interval
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Label1.ForeColor = Color.Red Then
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 24
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Label1.ForeColor = Color.Blue
ElseIf Label1.ForeColor = Color.Blue Then
Label1.ForeColor = Color.Red
End If
TextBox1.Text = TextBox1.Text + 1 'Incremenet the TextBox1 by 1
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Timer1.Stop() ' Stop the timer
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Start() 'Start the timer
End Sub
End Class

Output:

When the program executes, it starts blinking the WELCOME TO


JAVATPOINT.COM statement and counting the number to 1, as shown above. When the
number is odd, the color of the statement is Red, and when the number is even, the color of the
statement is Blue, as shown below.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 25


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

VB.NET PROGRESSBAR CONTROL


The Window ProgressBar control is used by the user to acknowledge the progress status of
some defined tasks, such as downloading a large file from the web, copying files, installing
software, calculating complex results, and more.
Let's create a ProgressBar by dragging a ProgressBar control from the toolbox and dropping it
to the Windows form.
Step 1: The first step is to drag the ProgressBar control from the toolbox and drop it on to the
Form.

Step 2: Once the ProgressBar is added to the Form, we can set various properties of the
ProgressBar by clicking on the ProgressBar control.

Properties of the ProgressBar Control


There are following properties of the VB.NET ProgressBar control.

Property Description

The BackgroundImage property is used to set the background


BackgroundImage
image in the progressbar control.

It is used to determine the progress status for a progress bar in


MarqueeAnimationSpeed
milliseconds.

The padding property is used to create a space between the


Padding edges of the progress bar by setting the value in the progressbar
control.

It is used to get or set a value in control that calls the


Step PerformStep method to increase the current state of the progress
bar by adding a defined step.

It is used to set the maximum length of the progress bar control


Maximum
in the windows form.

It is used to set or get the minimum value of the progress bar


Minimum
control in the windows form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 26


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

It obtains a value representing whether the progress bar control


AllowDrop
enables the user to be dragged onto the form.

It is used to set a value that represents how types the progress


Style
bar should be displayed on the Windows Form.

Methods of the ProgressBar Control

Event Description

ForeColor The ForeColor method is used to reset the forecolor to its default value.

The ToString method is used to display the progress bar control by returning
ToString
the string.

It is used to increase the current state of the progress bar control by defining
Increment
the specified time.

The PerformStep method is used to increase the progress bar by setting the
PerformStep
step specified in the ProgressBar property.

Events of the ProgressBar Control

Events Description

The Leave event occurs when the focus leaves the progress
Leave
bar control.

A MouseClick event occurred when the user clicked on the


MouseClick
progress bar control by the mouse.

When the background property changes to the progress bar


BackgroundImageChanged
control, the BackgroundImageChanged event changes.

It occurs when the property of the text is changed in the


TextChanged
progress bar control.

It occurs when the padding property is changed in the


PaddingChanged
progress bar control.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ProgressBar control properties, methods, and events in the VB.NET.
Let's create a program to display the progress status in the VB.NET Windows form.

Progressbr.vb
Public Class Progressbr

Private Sub Progressbr_Load(sender As Object, e As EventArgs) Handles MyBase.Load

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 27


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Me.Text = "javaTpoint.com" 'Set the title name for the form


Button1.Text = "Show"
Label1.Text = "Click to display the progress status of the ProgressBar"

Label1.ForeColor = ForeColor.Green
ProgressBar1.Visible = False
'create a progress bars
Dim Progressbr2 As ProgressBar = New ProgressBar()
'set the progressbar position
Progressbr2.Location = New Point(60, 70)

'set the values for Progressbr2


Progressbr2.Minimum = 0
Progressbr2.Maximum = 500
Progressbr2.Value = 470
'add the progress bar status to the form.
Me.Controls.Add(Progressbr2)

End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ProgressBar1.Visible = True
Dim i As Integer
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 300
For i = 0 To 300 Step 1

ProgressBar1.Value = i
If i > ProgressBar1.Maximum Then
i = ProgressBar1.Maximum
End If
Next
MsgBox("Successfully Completed")
End Sub
End Class

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 28


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Output:

Click on the Show button to display the progress status at run time in Windows Form.

And when the progress status reaches the progress bar's maximum value, it displays the
following message.

VB.NET SCROLLBARS CONTROL


A ScrollBar control is used to create and display vertical and horizontal scroll bars on the
Windows form. It is used when we have large information in a form, and we are unable to see
all the data. Therefore, we used VB.NET ScrollBar control. Generally, ScrollBar is of two
types: HScrollBar for displaying scroll bars and VScrollBar for displaying Vertical Scroll bars.
Let's create a ScrollBar control in the VB.NET Windows form using the following steps.
Step 1: The first step is to drag the HScrollBar and VScrollBar control from the toolbox and
drop it on to the form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 29


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Step 2: Once the ScrollBar is added to the form, we can set various properties of the ScrollBar
by clicking on the HScrollBar and VScrollBar control.

Properties of the ScrollBar Control


There are following properties of the VB.NET ScrollBar control.

Property Description

BackColor The BackColor property is used to set the back color of the scroll bar.

It is used to set or get the maximum value of the Scroll Bar control. By
Maximum
default, it is 100.

It is used to get or set the minimum value of the Scroll bar control. By
Minimum
default, it is 0.

It is used to obtain or set a value that will be added or subtracted from


SmallChange the property of the scroll bar control when the scroll bar is moved a short
distance.

As the name suggests, the AutoSize property is used to get or set a value
AutoSize representing whether the scroll bar can be resized automatically or not
with its contents.

It is used to obtain or set a value that will be added or subtracted from


LargeChange the property of the scroll bar control when the scroll bar is moved a large
distance.

It is used to obtain or set a value in a scroll bar control that indicates a


Value
scroll box's current position.

It is used to get the default input method Editor (IME) that are supported
DefaultImeMode
by ScrollBar controls in the Windows Form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 30


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Methods of the ScrollBar Control

Method Description

It is used to update the ScrollBar control using the


UpdateScrollInfo Minimum, maximum, and the value of LargeChange
properties.

OnScroll(ScrollEventArgs) It is used to raise the Scroll event in the ScrollBar Control.

It is used to raise the EnabledChanged event in the


OnEnabledChanged
ScrollBar control.

Select It is used to activate or start the ScrollBar control.

It is used to raise the ValueChanged event in the ScrollBar


OnValueChanged(EventArgs)
control.

Events of the ScrollBar Control

Event Description

The AutoSizeChanged event is found in the ScrollBar control when


AutoSizeChanged
the value of the AutoSize property changes.

Scroll The Scroll event is found when the Scroll control is moved.

It occurs in the ScrollBar control when the value of the text property
TextChangedEvent
changes.

A ValueChanged event occurs when the property of the value is


ValueChanged changed programmatically or by a scroll event in the Scrollbar
Control.

Furthermore, we can also refer to VB.NET Microsoft documentation to get a complete list
of ScrollBar control properties, methods, and events in the VB.NET.
Let's create a simple program to understand the use of ScrollBar Control in the VB.NET
Windows Forms.

ScrollBar.vb

Public Class ScrollBar


Private Sub ScrollBar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "javatpoint.com" 'Set the title for a Windows Form

Label1.Text = "Use of ScrollBar in Windows Form"


Label1.ForeColor = Color.Blue
Me.AutoScroll = True

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 31


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Me.VScrollBar1.Minimum = 0
Me.VScrollBar1.Maximum = 100
Me.VScrollBar1.Value = 0

Me.VScrollBar1.BackColor = Color.Blue
Me.HScrollBar1.Minimum = 0
Me.HScrollBar1.Maximum = 100
Me.HScrollBar1.Value = 35
End Sub
End Class

Output:

VB.NET COMBOBOX CONTROL


The ComboBox control is used to display more than one item in a drop-down list. It is a
combination of Listbox and Textbox in which the user can input only one item. Furthermore,
it also allows a user to select an item from a drop-down list.
Let's create a ComboBox control in the VB.NET Windows by using the following steps.
Step 1: We need to drag the combo box control from the toolbox and drop it to
the Windows form, as shown below.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 32


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Step 2: Once the ComboBox is added to the form, we can set various properties of the
ComboBox by clicking on the ComboBox control.

ComboBox Properties
There are following properties of the ComboBox control.

Property Description

The AllowSelection property takes the value that indicates whether


AllowSelection
the list allows selecting the list item.

It takes a value that represents how automatic completion work for


AutoCompleteMode
the ComboBox.

Created It takes a value that determines whether the control is created or not.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 33


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

DataBinding It is used to bind the data with a ComboBox Control.

The BackColor property is used to set the background color of the


BackColor
combo box control.

DataSource It is used to get or set the data source for a ComboBox Control.

FlatStyle It is used to set the style or appearance for the ComboBox Control.

The MaxDropDownItems property is used in the combo box control


MaxDropDownItems
to display the maximum number of items by setting a value.

It is used by the user to enter maximum characters in the editable


MaxLength
area of the combo box.

SelectedItem It is used to set or get the selected item in the ComboBox Control.

The Sorted property is used to sort all the items in the ComboBox by
Sorted
setting the value.

ComboBox Events

Events Description

FontChanged It occurs when the property of the font value is changed.

Format When the data is bound with a combo box control, a format event is
called.

SelectIndexChanged It occurs when the property value of SelectIndexChanged is changed.

HelpRequested When the user requests for help in control, the HelpRequested event
is called.

Leave It occurs when the user leaves the focus on the ComboBox Control.

MarginChanged It occurs when the property of margin is changed in the ComboBox


control.

Let's create a program to display the Calendar in the VB.NET Windows Form.

ComboBox_Control.vb

Public Class ComboBox_Control


Dim DT As Integer

Dim MM As String
Dim YY As Integer
Private Sub ComboBox_Control_Load(sender As Object, e As EventArgs) Handles M
yBase.Load

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 34


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Me.Text = "JavaTpoint.com"
Label1.Text = "Display Calendar"
Label2.Text = "Get Date"

Button1.Text = "Date"
Button2.Text = "Exit"
ComboBox1.Items.Add("Date")
ComboBox1.Items.Add("01")
ComboBox1.Items.Add("02")
ComboBox1.Items.Add("03")

ComboBox1.Items.Add("04")
ComboBox1.Items.Add("05")
ComboBox1.Items.Add("06")
ComboBox1.Items.Add("07")
ComboBox1.Items.Add("08")
ComboBox1.Items.Add("09")

ComboBox2.Items.Add("Month")
ComboBox2.Items.Add("January")
ComboBox2.Items.Add("February")
ComboBox2.Items.Add("March")
ComboBox2.Items.Add("May")
ComboBox2.Items.Add("June")
ComboBox2.Items.Add("July")

ComboBox3.Items.Add("Year")
ComboBox3.Items.Add("2016")
ComboBox3.Items.Add("2017")
ComboBox3.Items.Add("2018")
ComboBox3.Items.Add("2019")
ComboBox3.Items.Add("2020")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 35


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

DT = ComboBox1.Text
MM = ComboBox2.Text
YY = ComboBox3.Text

MsgBox("Month " & MM + vbCrLf + "Year " & YY)


End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
End
End Sub
End Class

Output:

Now select the day, month, and year from dropdown box and then click on the Date button to
display the date in the form.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 36


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

NUMERICUPDOWN CONTROL IN VB.NET


NumericUpDown is basically countered that the user can input a number within the specified
range. With the Help of NumericUpDown Control, we can enter numeric values, with
advanced features like up-down buttons and accelerating auto-repeat.

How to use NumericUpDown Control


Drag and drop NumericUpDown Control from the toolbox on window Form.

Code:
Public Class Form12
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs)

Handles NumericUpDown1.ValueChanged
'NumericUpDown valu will show in TextBox
TextBox1.Text = NumericUpDown1.Value
End Sub
End Class

By Default Maximum and Minimum value in NumericUpDown Control is set 100 and 0
respectively. You can also set Maximum and Minimum value in NumericUpDown Control. To
show the value in NumericUpDown.

Run the project

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 37


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

When you select the value in NumericUpDown1 then the ValueChanged event will fire and
selected value will show in the TextBox.

NumericUpDown Control Properties


DecimalPlaces: Gets or sets the number of decimal places to display in NumericUpDown
Control.

UpDownAlign: Set positions the arrow buttons on the left or the right side of the
NumericUpDown. Default value is Right.
Increment: Gets or sets the value to increment or decrement the NumericUpDown.
Private Sub Form12_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
'Increment the NumericUpDown value
NumericUpDown1.Increment = 5
End Sub

NumericUpDown value will be inrement 5 at each up button click.


GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 38
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Hexadecimal: Hexadecimal property used to show value in Hexadecimal format in


NumericUpDown. Default value is false.
Private Sub Form12_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
' allow to show value Hexadecimal format

NumericUpDown1.Hexadecimal = True
End Sub

TRACKBAR CONTROL
The TrackBar control is similar to the ScrollBar control, but it lacks the granularity of
ScrollBar. Suppose that you want the user of an application to supply a value in a specific
range, such as the speed of a moving object. Moreover, you don’t want to allow extreme
precision; you need only a few settings, as shown in the examples in this page. The user can set
the control’s value by sliding the indicator or by clicking on either side of the indicator.
Granularity is how specific youwant to be inmeasuring. Inmeasuring distances between towns,
a granularity of a mile is quite adequate. In measuring (or specifying) the dimensions of a
building, the granularity could be on the order of a foot or an inch. The TrackBar control lets
you set the type of granularity that’s necessary for your application.
Similar to the ScrollBar control, SmallChange and LargeChange properties are available.
SmallChange is the smallest increment by which the Slider value can change. The user can
change the slider by the SmallChange value only by sliding the indicator. (Unlike the ScrollBar
control, there are no arrows at the two ends of the Slider control.) To change the Slider’s value
by LargeChange, the user can click on either side of the indicator.

The TrackBar Control Inches Exercise


Figure 4.1 demonstrates a typical use of the TrackBar control. The form in the figure is an
element of a program’s user interface that lets the user specify a distance between 0 and 10
inches in increments of 0.2 inches. As the user slides the indicator, the current value is
displayed on a Label control below the TrackBar. If you open the Inches application, you’ll
notice that there are more stops than there are tick marks on the control. This is made possible
with the TickFrequency property, which determines the frequency of the visible tick marks.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 39


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Figure 4.1 – A typical use of TrackBar control in VB.NET – The Inches Application
You might specify that the control has 50 stops (divisions), but that only 10 of them will be
visible. The user can, however, position the indicator on any of the 40 invisible tick marks.
You can think of the visible marks as the major tick marks, and the invisible ones as the minor
tick marks. If the TickFrequency property is 5, only every fifth mark will be visible. The
slider’s indicator, however, will stop at all tick marks.
When using the TrackBar control on your interfaces, you should set the TickFrequency
property to a value that helps the user select the desired setting. Too many tick marks are
confusing and difficult to read. Without tick marks, the control isn’t of much help. You might
also consider placing a few labels to indicate the value of selected tick marks, as I have done in
this example.
The properties of the TrackBar control in the Inches application are as follows:
Minimum = 0
Maximum = 50

SmallChange = 1
LargeChange = 5
TickFrequency = 5
The TrackBar needs to cover a range of 10 inches in increments of 0.2 inches. If you set the
SmallChange property to 1, you have to set LargeChange to 5. Moreover, the TickFrequency is
set to 5, so there will be a total of five divisions in every inch. The numbers below the tick
marks were placed there with properly aligned Label controls.
The label at the bottom needs to be updated as the TrackBar’s value changes. This is signaled
to the application with the Change event, which occurs every time the value of the control
changes, either through scrolling or from within your code. The ValueChanged event handler
of the TrackBar control is shown next:
Private Sub TrackBar1_ValueChanged(...) Handles TrackBar1.ValueChanged
lblInches.Text = "Length in inches = " & _

Format(TrackBar1.Value / 5, "#.00")

End Sub
The Label controls below the tick marks can also be used to set the value of the control. Every
time you click one of the labels, the following statement sets the TrackBar control’s value.
Notice that all the Label controls’ Click events are handled by a common handler:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 40


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Private Sub Label Click(...) _


Handles Label1.Click, Label9.Click
TrackBar1.Value = sender.text * 5

End Sub

VB.NET FUNCTIONS
In VB.NET, the function is a separate group of codes that are used to perform a specific task
when the defined function is called in a program. After the execution of a function, control
transfer to the main() method for further execution. It returns a value. In VB.NET, we can
create more than one function in a program to perform various functionalities. The function is
also useful to code reusability by reducing the duplicity of the code. For example, if we need to
use the same functionality at multiple places in a program, we can simply create a function and
call it whenever required.
The syntax to define a function is:
[Access_specifier ] Function Function_Name [ (ParameterList) ] As Return_Type
[ Block of Statement ]

Return return_val
End Function
Where,

 Access_Specifier: It defines the access level of the function such as public, private, or
friend, Protected function to access the method.
 Function_Name: The function_name indicate the name of the function that should be
unique.
 ParameterList: It defines the list of the parameters to send or retrieve data from a
method.
 Return_Type: It defines the data type of the variable that returns by the function.
The following are the various ways to define the function in a VB.NET.

Public Function add() As Integer


' Statement to be executed
End Function
Private Function GetData( ByVal username As String) As String
' Statement to be executed

End Function
Public Function GetData( ByVal username As String, ByVal userId As Integer) As String'
Statement to be executed
End Function

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 41


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Example: Write a program to find the sum and subtraction of two numbers using the function.

Find_Sum.vb

Imports System

Module Find_Sum
' Create the SumOfTwo() Function and pass the parameters.
Function SumOfTwo(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
' Define the local variable.
Dim sum As Integer = 0
sum = n1 + n2

Return sum
End Function
Function SubtractionOfTwo(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
' Define the local variable.
Dim subtract As Integer
subtract = n1 - n2

Return subtract
End Function
Sub Main()
' Define the local variable a and b.
Dim a As Integer = 50
Dim b As Integer = 20

Dim total, total1 As Integer


Console.WriteLine(" First Number is : {0}", a)
Console.WriteLine(" Second Number is : {0}", b)
total = SumOfTwo(a, b) 'call SumOfTwo() Function
total1 = SubtractionOfTwo(a, b) 'call SubtractionOfTwo() Function
Console.WriteLine(" Sum of two number is : {0}", total)

Console.WriteLine(" Subtraction of two number is : {0}", total1)


Console.WriteLine(" Press any key to exit...")
Console.ReadKey()

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 42


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

End Sub
End Module

Output:

In the above example, we have defined a SumOfTwo() and SubtractionOfTwo() function to


add and subtract two predefined numbers. When the functions are called in the main() method,
each function is executed and returns the sum and subtraction of two numbers, respectively.

RECURSIVE FUNCTION
When a function calls itself until the defined condition is satisfied, it is known as a recursive
function. A recursive function is useful for solving many mathematical tasks such as
generating the Fibonacci series, the factorial of a number, etc.
Let's create a program to calculate the factorial of a number using the recursive function.

Factorial_function.vb

Imports System
Module Factorial_function
' Create a Fact() function
Function Fact(ByVal num As Integer) As Integer
If (num = 0) Then
Return 0
ElseIf (num = 1) Then
Return 1
Else
Return num * Fact(num - 1)
End If
End Function
Sub Main()

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 43


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

' Define the local variable as integer


Dim n, f As Integer
Console.WriteLine(" Enter the number you want to calculate factorial")

n = Console.ReadLine() 'Accept a number


f = Fact(n) 'call Fact() function
Console.WriteLine(" Factorial is : {0}", f)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub

End Module

Output:

Passing Array as a Parameter


Let's create a program that parses an array as a pass parameters in a function.

Array_Parameter.vb

Imports System
Module array_Parameter
Function AddPara(ByVal Arr As Integer(), ByVal size As Integer) As Double
'Declare a local variable.
Dim i As Integer

Dim avg As Double


Dim Sum As Integer = 0
For I = 0 To size - 1
Sum = Sum + Arr(i)
Next
avg = Sum / size

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 44


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Return avg
End Function
Sub Main()

Dim arrays As Integer() = {50, 10, 20, 5, 4, 25}


Dim getAvg As Double
getAvg = AddPara(arrays, 6)
Console.WriteLine("Average sum of array element is {0}", getAvg)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()

End Sub
End Module

Output:

VB.NET SUB
A Sub procedure is a separate set of codes that are used in VB.NET programming to execute a
specific task, and it does not return any values. The Sub procedure is enclosed by the Sub and
End Sub statement. The Sub procedure is similar to the function procedure for executing a
specific task except that it does not return any value, while the function procedure returns a
value.
Following is the syntax of the Sub procedure:
[Access_Specifier ] Sub Sub_name [ (parameterList) ]
[ Block of Statement to be executed ]

End Sub
Where,
o Access_Specifier: It defines the access level of the procedure such as public, private or
friend, Protected, etc. and information about the overloading, overriding, shadowing to
access the method.
o Sub_name: The Sub_name indicates the name of the Sub that should be unique.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 45


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

o ParameterList: It defines the list of the parameters to send or retrieve data from a
method.

The following are the different ways to define the types of Sub method.
Public Sub getDetails()
' Statement to be executed
End Sub
Private Sub GetData( ByVal username As String) As String
' Statement to be executed

End Sub
Public Function GetData1( ByRef username As String, ByRef userId As Integer)
' Statement to be executed
End Sub
Example: Write a simple program to pass the empty, a single or double parameter of Sub
procedure in the VB.NET.

Sub_Program.vb
Module Sub_Program
Sub sample()
Console.WriteLine("Welcome to JavaTpoint")
End Sub
Sub circle(ByVal r As Integer)
Dim Area As Integer
Const PI = 3.14
Area = PI * r * r
Console.WriteLine(" Area Of circle is : {0}", Area)
End Sub
' Create the SumOfTwo() Function and pass the parameters.
Sub SumOfTwo(ByVal n1 As Integer, ByVal n2 As Integer)
' Define the local variable.
Dim sum As Integer = 0
sum = n1 + n2
Console.WriteLine(" Sum of two number is : {0}", sum)
End Sub
Sub SubtractionOfTwo(ByVal n1 As Integer, ByVal n2 As Integer)
' Define the local variable.
Dim subtract As Integer
subtract = n1 - n2
Console.WriteLine(" Subtraction of two number is : {0}", subtract)
End Sub
Sub MultiplicationOfTwo(ByVal n1 As Integer, ByVal n2 As Integer)
' Define the local variable.
Dim multiply As Integer
multiply = n1 * n2
Console.WriteLine(" Multiplication of two number is : {0}", multiply)
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 46
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

End Sub
Sub Main()
' Define the local variable a, b and rad.
Dim a, b, rad As Integer
sample() ' call sample() procedure
Console.WriteLine(" Please enter the First Number : ")
a = Console.ReadLine()
Console.WriteLine(" Second Number is : ")
b = Console.ReadLine()
SumOfTwo(a, b) 'call SumOfTwo() Function
SubtractionOfTwo(a, b) 'call SubtractionOfTwo() Function
MultiplicationOfTwo(a, b) 'call MultiplicationOfTwo() Function
Console.WriteLine(" Enter the radius of circle : ")
rad = Console.ReadLine()
circle(rad)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:

In the VB.NET programming language, we can pass parameters in two different ways:
o Passing parameter by Value
o Passing parameter by Reference

PASSING PARAMETER BY VALUE


In the VB.NET, passing parameter by value is the default mechanism to pass a value in the Sub
method. When the method is called, it simply copies the actual value of an argument into the
formal method of Sub procedure for creating a new storage location for each parameter.
Therefore, the changes made to the main function's actual parameter that do not affect the Sub
procedure's formal argument.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 47


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Syntax:
Sub Sub_method( ByVal parameter_name As datatype )
[ Statement to be executed]
End Sub

In the above syntax, the ByVal is used to declare parameters in a Sub procedure.
Let's create a program to understand the concept of passing parameter by value.

Passing_value.vb
Imports System
Module Passing_value
Sub Main()
' declaration of local variable
Dim num1, num2 As Integer
Console.WriteLine(" Enter the First number")
num1 = Console.ReadLine()
Console.WriteLine(" Enter the Second number")
num2 = Console.ReadLine()
Console.WriteLine(" Before swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" Before swapping the value of 'num2' is {0}", num2)
Console.WriteLine()
'Call a function to pass the parameter for swapping the numbers.
swap_value(num1, num2)
Console.WriteLine(" After swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" After swapping the value of 'num2' is {0}", num2)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
' Create a swap_value() method
Sub swap_value(ByVal a As Integer, ByVal b As Integer)
' Declare a temp variable
Dim temp As Integer
temp = a ' save the value of a to temp
b = a ' put the value of b into a
b = temp ' put the value of temp into b
End Sub
End Module

Output:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 48


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

PASSING PARAMETER BY REFERENCE


A Reference parameter is a reference of a variable in the memory location. The reference
parameter is used to pass a reference of a variable with ByRef in the Sub procedure. When we
pass a reference parameter, it does not create a new storage location for the sub method's
formal parameter. Furthermore, the reference parameters represent the same memory location
as the actual parameters supplied to the method. So, when we changed the value of the formal
parameter, the actual parameter value is automatically changed in the memory.
The syntax for the passing parameter by Reference:
Sub Sub_method( ByRef parameter_name, ByRef Parameter_name2 )
[ Statement to be executed]
End Sub
In the above syntax, the ByRef keyword is used to pass the Sub procedure's reference
parameters.
Let's create a program to swap the values of two variables using the ByRef keyword.

Passing_ByRef.vb
Imports System
Module Passing_ByRef
Sub Main()
' declaration of local variable
Dim num1, num2 As Integer
Console.WriteLine(" Enter the First number")
num1 = Console.ReadLine()
Console.WriteLine(" Enter the Second number")
num2 = Console.ReadLine()
Console.WriteLine(" Before swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" Before swapping the value of 'num2' is {0}", num2)
Console.WriteLine()
'Call a function to pass the parameter for swapping the numbers.
swap_Ref(num1, num2)
Console.WriteLine(" After swapping the value of 'num1' is {0}", num1)
Console.WriteLine(" After swapping the value of 'num2' is {0}", num2)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
' Create a swap_Ref() method
Sub swap_Ref(ByRef a As Integer, ByRef b As Integer)
' Declare a temp variable
Dim temp As Integer
temp = a ' save the value of a to temp
a = b ' put the value of b into a
b = temp ' put the value of temp into b
End Sub
End Module

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 49


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Output:

VB.NET - DATABASE ACCESS


Applications communicate with a database, firstly, to retrieve the data stored there and present
it in a user-friendly way, and secondly, to update the database by inserting, modifying and
deleting data.

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that
is used by the .Net applications for retrieving, accessing and updating data.

ADO.Net Object Model


ADO.Net object model is nothing but the structured process flow through various components.
The object model can be pictorially described as −

The data residing in a data store or database is retrieved through the data provider. Various
components of the data provider retrieve data for the application and update data.
An application accesses data either through a dataset or a data reader.
 Datasets store data in a disconnected cache and the application retrieves data from it.
 Data readers provide data to the application in a read-only and forward-only mode.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 50


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Data Provider
A data provider is used for connecting to a database, executing commands and retrieving data,
storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects −

Sr.No. Objects & Description

1 Connection -This component is used to set up a connection with a data source.

Command - A command is a SQL statement or a stored procedure used to


2
retrieve, insert, delete or modify data in a data source.

DataReader -Data reader is used to retrieve data from a data source in a read-only
3
and forward-only mode.

DataAdapter -This is integral to the working of ADO.Net since data is transferred


to and from a database through a data adapter. It retrieves data from a database
4
into a dataset and updates the database. When changes are made to the dataset, the
changes in the database are actually done by the data adapter.

There are following different types of data providers included in ADO.Net


 The .Net Framework data provider for SQL Server - provides access to Microsoft SQL
Server.
 The .Net Framework data provider for OLE DB - provides access to data sources
exposed by using OLE DB.
 The .Net Framework data provider for ODBC - provides access to data sources exposed
by ODBC.
 The .Net Framework data provider for Oracle - provides access to Oracle data source.
 The EntityClient provider - enables accessing data through Entity Data Model (EDM)
applications.

DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of records that
are retrieved from a database. When a connection is established with the database, the data
adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset,
the connection with the database is closed. This is called the 'disconnected architecture'. The
dataset works as a virtual database containing tables, rows, and columns.
The following diagram shows the dataset object model −

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 51


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

The DataSet class is present in the System.Data namespace. The following table describes all
the components of DataSet −

Sr.No. Components & Description

1 DataTableCollection - It contains all the tables retrieved from the data source.

DataRelationCollection - It contains relationships and the links between tables in


2
a data set.

ExtendedProperties - It contains additional information, like the SQL statement


3
for retrieving data, time of retrieval, etc.

DataTable- It represents a table in the DataTableCollection of a dataset. It


4 consists of the DataRow and DataColumn objects. The DataTable objects are case-
sensitive.

DataRelation -It represents a relationship in the DataRelationshipCollection of the


5 dataset. It is used to relate two DataTable objects to each other through the
DataColumn objects.

6 DataRowCollection - It contains all the rows in a DataTable.

DataView - It represents a fixed customized view of a DataTable for sorting,


7
filtering, searching, editing and navigation.

PrimaryKey -It represents the column that uniquely identifies a row in a


8
DataTable.

DataRow -It represents a row in the DataTable. The DataRow object and its
properties and methods are used to retrieve, evaluate, insert, delete, and update
9
values in the DataTable. The NewRow method is used to create a new row and the
Add method adds a row to the table.

10 DataColumnCollection - It represents all the columns in a DataTable.

11 DataColumn - It consists of the number of columns that comprise a DataTable.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 52


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Connecting to a Database
The .Net Framework provides two types of Connection classes −
 SqlConnection − designed for connecting to Microsoft SQL Server.
 OleDbConnection − designed for connecting to a wide range of databases, like
Microsoft Access and Oracle.

Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named
testDB. Please consult 'SQL Server' tutorial for creating databases and database tables in SQL
Server.
Let us connect to this database. Take the following steps −

 Select TOOLS → Connect to Database

 Select a server name and the database name in the Add Connection dialog box.

 Click on the Test Connection button to check if the connection succeeded.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 53


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

 Add a DataGridView on the form.

 Click on the Choose Data Source combo box.


 Click on the Add Project Data Source link.

 This opens the Data Source Configuration Wizard.


 Select Database as the data source type

 Choose DataSet as the database model.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 54


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

 Choose the connection already set up.

 Save the connection string.

 Choose the database object, Customers table in our example, and click the Finish
button.

 Select the Preview Data link to see the data in the Results grid −

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 55


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

When the application is run using Start button available at the Microsoft Visual Studio tool
bar, it will show the following window −

Example 2
So far, we have used tables and databases already existing in our computer. In this example, we
will create a table, add columns, rows and data into it and display the table using a
DataGridView object.
Take the following steps −

 Add a DataGridView control and a button in the form.


 Change the text of the button control to 'Fill'.
 Add the following code in the code editor.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Private Function CreateDataSet() As DataSet
'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 56
KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

Private Function CreateStudentTable() As DataTable


Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub
'adding data into the table
Private Sub AddNewRow(ByRef table As DataTable, ByRef id As Integer,_
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = table.NewRow()
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End Class

When the above code is executed and run


using Start button available at the Microsoft Clicking the Fill button displays the table on
Visual Studio tool bar, it will show the the data grid view control −
following window –

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 57


KAVITHA RAJALAKSHMI D APPLICATION DEVELOPMENT ON .NET

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 58

You might also like