Application Development On
Application Development On
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.
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:-
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.
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”.
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.
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:-
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:-
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.
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:-
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.
Output:-
BUTTON
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.
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:-
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.
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.
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.
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.
Properties Description
Cursor It is used to set the cursor image when it hovers over the 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.
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.
MinimumSize It is used to set the minimum height and width of 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
DoubleClick
DoubleClick The DoubleClick event is activated when a user double clicks on
the form.
Load The load event is used to load a form before it is first displayed.
Shown It is activated whenever the form is displayed for the first time.
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.
Form1.vb
' 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
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
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.
Properties Description
Name The Name property is used to set the name of the control.
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 Description
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 Description
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:
Step 2: Once the ProgressBar is added to the Form, we can set various properties of the
ProgressBar by clicking on the ProgressBar control.
Property Description
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 Description
The Leave event occurs when the focus leaves the progress
Leave
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
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)
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
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.
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.
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.
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 get the default input method Editor (IME) that are supported
DefaultImeMode
by ScrollBar controls in the Windows Form.
Method Description
Event Description
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.
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
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:
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
Created It takes a value that determines whether the control is created or not.
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.
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
Format When the data is bound with a combo box control, a format event is
called.
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.
Let's create a program to display the Calendar in the VB.NET Windows Form.
ComboBox_Control.vb
Dim MM As String
Dim YY As Integer
Private Sub ComboBox_Control_Load(sender As Object, e As EventArgs) Handles M
yBase.Load
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
DT = ComboBox1.Text
MM = ComboBox2.Text
YY = ComboBox3.Text
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.
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.
When you select the value in NumericUpDown1 then the ValueChanged event will fire and
selected value will show in the TextBox.
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
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.
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:
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.
End Function
Public Function GetData( ByVal username As String, ByVal userId As Integer) As String'
Statement to be executed
End Function
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
End Sub
End Module
Output:
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()
End Module
Output:
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
Return avg
End Function
Sub Main()
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.
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
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:
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
Output:
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.
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.
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 −
DataReader -Data reader is used to retrieve data from a data source in a read-only
3
and forward-only mode.
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 −
The DataSet class is present in the System.Data namespace. The following table describes all
the components of DataSet −
1 DataTableCollection - It contains all the tables retrieved from the data source.
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.
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 a server name and the database name in the Add Connection dialog box.
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 −
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 −