Computer Engineering
PRACTICAL MATERIAL 11
Computer
Programming
Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
Phone : 5639122/6634373/6635046/6630088
Website : www.moecdc.gov.np
Feedback Copy
Technical and Vocational Stream
Practical Materials
Computer Programming
(Grade 11)
Secondary Level
Computer Engineering
Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
Publisher: Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
© Publisher
Layout by Khados Sunuwar
All rights reserved. No part of this publication may be reproduced, stored in a
retrieval system or transmitted, in any other form or by any means for commercial
purpose without the prior permission in writing of Curriculum Development
Centre.
Preface
The curriculum and curricular materials have been developed and revised on a regular
basis with the aim of making education objective-oriented, practical, relevant and job
oriented. It is necessary to instill the feelings of nationalism, national integrity and
democratic spirit in students and equip them with morality, discipline and self-reliance,
creativity and thoughtfulness. It is essential to develop in them the linguistic and
mathematical skills, knowledge of science, information and communication
technology, environment, health and population and life skills. It is also necessary to
bring in them the feeling of preserving and promoting arts and aesthetics, humanistic
norms, values and ideals. It has become the need of the present time to make them
aware of respect for ethnicity, gender, disabilities, languages, religions, cultures,
regional diversity, human rights and social values so as to make them capable of
playing the role of responsible Citizens with applied technical and vocational
knowledge and skills. This practical material for Computer Engineering has been
developed in line with the Secondary Level Computer Engineering Curriculum so as
to facilitate the students in their classroom based practicum and on the job training by
incorporating the recommendations and feedback obtained from various schools,
workshops and seminars, interaction programs attended by teachers, students and
parents.
In Bringing out the practical material in this form, the contribution of the Director
General of CDC Dr. Lekhnath Poudel and Pro, Dr. Subarna Shakya, Bibha Sthapit,
Kumar Prasun, Anil Barma, Dr. Sanjiv Pandey, Romakanta Pandey, Dinesha Khatri,
Trimandir Prajapati, Shankar Yadav, Jonsan Khadka and Ramesha Rimal is highly
acknowledged. The book is written by Yogesh Parajuli and the subject matter of the
book was edited by Badrinath Timalsina and Khilanath Dhamala. CDC extends sincere
thanks to all those who have contributed to developing this practical book.
This book is a supplimentary practical material for students and teachers. In addition
they have to make use of other relevnt materials to ensure all the learning outcomes
set in the curriculum. The teachers, students and all other stakeholders are expected to
make constructive comments and suggestions to make it a more useful practical
material.
2077 BS Ministry of Education, Science and Technology
Curriculum Development Centre
Table of Contents
Unit - 1 ------------------------------------------------------------------------------------------ 1
Develop a flowchart, algorithm and Pseudo code with the concept of sequence ------ 1
Unit - 2 ------------------------------------------------------------------------------------------ 5
Installation of Java Tools --------------------------------------------------------------------- 5
Unit - 3 ----------------------------------------------------------------------------------------- 14
Demonstrate class, object, methods, constructor, and Inheritance,--------------------- 14
Unit - 4 ----------------------------------------------------------------------------------------- 17
Create and import Java Package and Sub-Package. -------------------------------------- 17
Unit - 5 ----------------------------------------------------------------------------------------- 18
Create I/O Stream program ------------------------------------------------------------------ 18
Unit - 6 ----------------------------------------------------------------------------------------- 20
Install VB.NET Program -------------------------------------------------------------------- 20
Unit - 7 ----------------------------------------------------------------------------------------- 23
Console Program to declare variables and data types ------------------------------------ 23
Unit - 9 ----------------------------------------------------------------------------------------- 41
Create Class, Objects, Constructor and Methods ----------------------------------------- 41
Unit - 10 ---------------------------------------------------------------------------------------- 51
Develop Database Connection Program with Insert, Update, Delete and Search
Options. ---------------------------------------------------------------------------------------- 51
Unit - 1
Develop a flowchart, algorithm and Pseudo code with
the concept of sequence
Iteration, loops
We learned theoritical aspects of flowcharts algorithm and pseudo code in the
earlier lesson.
We will learn and practice the practical aspects of these contents in this unit.
Flowchart
The graphical representation of flow of program is a flowchart
The symbols to draw flowchart are as follows:
The basic flowchart are as follows:
Computer Programming : Practical Book 1
Flowchart to add two numbers
The flowchart to calculate personal Interest is as follows
The flowchart to calculate odd or even numbers.
2 Computer Programming : Practical Book
Algorithm
An algorithm is a set of steps of operations to solve a problem performing calculation,
data processing, and automated reasoning tasks. An algorithm is an efficient method
that can be expressed within finite amount of time and space.
Algorithm for adding two numbers
Step 1: start
Step2: input two numbers x and y
Step3: read two numbers x and y
Step4: z=x+y
Step5: display result z
Step6: stop
Computer Programming Practical 3
Algorithm for calculating simple Interest
Step 1: start
Step 2: input principal, time and rate p,t,r
Step 3: read the p, t, and r
Step 4: Interest = (p*t*r)/100
Step 5: Display interest
Step 6: stop
Algorithm to print odd or even number
Step 1: Start
Step 2: input Number
Step 3: If Number%2 == 0 Then
Print: Number is an Even Number.
Else
Print: Number is an Odd Number.
Step 4: Exit
Pseudocode
Pseudocode is an informal way of programming description that does not require any
strict programming language syntax or underlying technology considerations
Pseudocode for finding the area of rectangle
Input length breadth
Calculate area= length* breadth
Output area
4 Computer Programming : Practical Book
Unit - 2
Installation of Java Tools
Console program to demonstrate conditional and looping statements.
Installation of Java Tools
For the installation of Java first of all we need to download Java from the internet the
website for latest java download can be found at https://www.oracle.com/java/
technologies/javase-downloads.html and after downloads the steps are as follows
Run the installer “jdk-8u141-windows-x64.exe”
The following wizard will be displayed that will take through the installation. Click
“Next”.
Keep the defaults and click “Next”.
Computer Programming Practical 5
Java will be installed at C:\Program Files.
6 Computer Programming : Practical Book
Java is being installed.
After installation of Java is completed the following windows is seen. One can get
documents related to java by clicking “Next Steps”.
Computer Programming Practical 7
Click “close” to finish the installation.
Before working with Java it is required to set path of java in environment variables.
Follow these steps:
From “Advance system settings” ->”Advanced” ->select “Environment Variables”
Put value of JAVA_HOME as absolute path where java is installed.
Ex: C:\Program Files\Java\jdk1.8.0_141
8 Computer Programming : Practical Book
Select “path” and click on “edit”.
Create a new path by clicking “new” and adding “bin” to path.
New->”%JAVA_HOME%\bin”->OK
Java environment variable is set.
So by following the above procedure Java will be installed and java environment
variables will be set.
Console program to demonstrate conditional and looping statements
Program to check greatest among two numbers
public class Sample{
public static void main(String args[]) {
int a = 80, b = 30;
if (b > a) {
System.out.println("b is greater");
} else {
System.out.println("a is greater");
Computer Programming Practical 9
}
}
}
Output
a is greater
Program to illustrate if else if statement
public class Sample {
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}
Output
Both are equal
10 Computer Programming : Practical Book
Program to illustrate Switch statement
public class Sample {
public static void main(String args[]) {
int a = 5;
switch (a) {
case 1:
System.out.println("You chose One");
break;
case 2:
System.out.println("You chose Two");
break;
case 3:
System.out.println("You chose Three");
break;
case 4:
System.out.println("You chose Four");
break;
case 5:
System.out.println("You chose Five");
break;
default:
System.out.println("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
Computer Programming Practical 11
}
Output
You choose five
Basic example to illustrate while loop
public class Sample {
public static void main(String args[]) {
int n = 1, times = 5;
while (n <= times) {
System.out.println("Java while loops:" + n);
n++;
}
}
}
Output
Java while loops: 1
Java while loops: 2
Java while loops: 3
Java while loops: 4
Java while loops: 5
The basic program to illustrate do-while loop in java is
public class Sample {
public static void main(String args[]) {
int n = 1, times = 0;
12 Computer Programming : Practical Book
do {
System.out.println("Java do while loops:" + n);
n++;
} while (n <= times);
}
}
Output
Java do while loops: 1
The basic program to illustrate for loop is
public class Sample {
public static void main(String args[]) {
int n = 1, times = 5;
for (n = 1; n <= times; n = n + 1) {
System.out.println("Java for loops:" + n);
}
}
}
Output
Java for loops: 1
Java for loops: 2
Java for loops: 3
Java for loops: 4
Java for loops: 5
Computer Programming Practical 13
Unit - 3
Demonstrate class, object, methods, constructor, and
Inheritance,
Class and object Demonstration
Class Student{
int id;
string name;
Public static void main(String args[]){
Student s1=new Student(); //creating an object of student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Method Demonstration
public class Example {
public static void main(String argu[]) {
int val1 = 62;
int val2 = 8;
int res = fun(val1, val2);
System.out.println("Result is: " + res);
}
public static int fun(int g1, int g2) {
int ans;
ans = g1 + g2;
return ans;
14 Computer Programming : Practical Book
}
}
Output
Result is: 70
Constructor Demonstration
import java.util.*;
import java.lang.*;
import java.io.*;
class clerk{
int roll=101;
String grade="Manager";
void display(){System.out.println(roll+" "+grade);}
public static void main(String args[]){
clerk c1=new clerk();
clerk c2=new clerk();
c1.display();
c2.display();
}
}
Inheritance Demonstration
class Teacher {
void teach() {
System.out.println("Teaching subjects");
}
Computer Programming Practical 15
}
class Students extends Teacher {
void listen() {
System.out.println("Listening to teacher");
}
}
class CheckForInheritance {
public static void main(String args[]) {
Students s1 = new Students();
s1.teach();
s1.listen();
}
}
16 Computer Programming : Practical Book
Unit - 4
Create and import Java Package and Sub-Package.
Console Program to implement and apply interface.
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
Computer Programming Practical 17
Unit - 5
Create I/O Stream program
Public final class console extends object
The basic example of java console is
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
The output of the following will be
Enter your name: Yogesh
Welcome Yogesh
Embed a Java Applet Program to a HTML File.
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 50, 25);
18 Computer Programming : Practical Book
}
}
Now we have to create an html file that includes the applet. The html file must be
placed in the same directory as the java file. The HTML file must contain the following
code:
<html>
<head>
<TITLE> A Simple Program </TITLE>
</head>
<body>
Here is the output of my program:
<applet code="HelloWorld.class" width="150" height="25"></applet>
</body>
</html>
Computer Programming Practical 19
Unit - 6
Install VB.NET Program
Step 1 - Make sure your computer is ready for Visual Studio
Before you begin installing Visual Studio:
Apply the latest Windows updates. These updates ensure that your computer has both
the latest security updates and the required system components for Visual Studio.
Step 2 - Download Visual Studio
Next, download the Visual Studio bootstrapper file.
To do so, choose the following button, choose the edition of Visual Studio that you
want, choose Save, and then choose Open folder.
Step 3 - Install the Visual Studio installer
Run the bootstrapper file to install the Visual Studio Installer. This new lightweight
installer includes everything you need to both install and customize Visual Studio.
From your Downloads folder, double-click the bootstrapper that matches or is similar
to one of the following files:
vs_community.exe for Visual Studio Community( as other editions are not preferrable
Step 4 - Choose workloads
After the installer is installed, you can use it to customize your installation by selecting
the feature sets—or workloads—that you want. Here's how.
20 Computer Programming : Practical Book
Find the workload you want in the Visual Studio Installer.
For example, choose the "ASP.NET and web development" workload. It comes with
the default core editor, which includes basic code editing support for over 20
Computer Programming Practical 21
languages, the ability to open and edit code from any folder without requiring a project,
and integrated source code control.
After you choose the workload(s) you want, choose Install. After installation you are
ready to go for development.
22 Computer Programming : Practical Book
Unit - 7
Console Program to declare variables and data types
using System;
namespace DeclaringConstants {
class Program {
static void Main(string[] args) {
char ch = 'g';
int xy = 6, roll = 42;
byte b = 22;
double pi = 3.14159;
float salary = 20000.0f;
}
}
}
Console Program to demonstrate conditional and looping statements.
While loop
using System;
class Example
{
public static void Main()
{
int cntr = 1;
while (cntr<= 5)
{
Computer Programming Practical 23
Console.WriteLine(" Hello World "+cntr);
cntr++;
}
}
}
The output of the program will be
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
For loop
using System;
class Example
{
public static void Main()
{
for (int cntr = 1; cntr<= 5; cntr++)
Console.WriteLine(" Hello world "+cntr);
}
}
The output of the following will be:
Hello World 1
Hello World 2
24 Computer Programming : Practical Book
Hello World 3
Hello World 4
Hello World 5
Do-while loop
using System;
class Example
{
public static void Main()
{
int cntr = 11;
do
{
Console.WriteLine(" Hello world "+cntr);
cntr++;
}
while (cntr< 10);
}
}
The output will be
Hello world 11
Console program to demonstrate Sub and Functions.
using System;
namespace FunctionExample
{
Computer Programming Practical 25
class Program
{
// User defined function
public string Show(string message)
{
Console.WriteLine("Inside Show Function");
return message;
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program();
string message = program.Show("Rahul Kumar");
Console.WriteLine("Hello "+message);
}
}
}
Use MsgBox and InputBox with properties
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
' Input Box with only Prompt
InputBox("Enter a number")
26 Computer Programming : Practical Book
' Input Box with a Title
a = InputBox("Enter a Number","Enter Value")
msgbox a
' Input Box with a Prompt,Title and Default value
a = InputBox("Enter a Number","Enter Value",123)
msgbox a
' Input Box with a Prompt,Title,Default and XPos
a = InputBox("Enter your name","Enter Value",123,700)
msgbox a
' Input Box with a Prompt,Title and Default and YPos
a = InputBox("Enter your name","Enter Value",123,,500)
msgbox a
</script>
</body>
</html>
Design Form and develop a simple calculator.
Public Class calculator
' two numbers to do the calc
Dim num1, num2 As Double
' check if an operator is clicked for the first time
Dim oprClickCount As Integer = 0
' check if an operator is clicked befor
Dim isOprClick As Boolean = False
' check if equal is clicked befor
Dim isEqualClick As Boolean = False
Computer Programming Practical 27
' get the operator
Dim opr As String
Private Sub calculator_Load(sender As Object, e AsEventArgs) Handles
MyBase.Load
' add click event to all button in the form
For Each c As Control In Controls
' if the control is button
If c.GetType() = GetType(Button) Then
If Not c.Text.Equals("Reset") Then
' add action to the button
AddHandlerc.Click, AddressOfbtn_Click
End If
End If
Next
End Sub
' create a button click event
Private Sub btn_Click(sender As Object, e As EventArgs)
Dim button As Button = sender
If Not isOperator(button) Then
' if number
If isOprClick Then
' if an opr is clicked
' get and convert to double textbox text
num1 = Double.Parse(TextBox1.Text)
' clear textbox text
28 Computer Programming : Practical Book
TextBox1.Text = ""
End If
If Not TextBox1.Text.Contains(".") Then
' if "." not already in the textbox
If TextBox1.Text.Equals("0") AndAlso Not button.Text.Equals(".") Then
TextBox1.Text = button.Text
isOprClick = False
Else
TextBox1.Text += button.Text
isOprClick = False
End If
ElseIf Not button.Text.Equals(".") Then
' if the button is not a "."
TextBox1.Text += button.Text
isOprClick = False
End If
Else
' if operator
If oprClickCount = 0 Then
' if we click on an operator for the first time
oprClickCount += 1
num1 = Double.Parse(TextBox1.Text)
opr = button.Text
isOprClick = True
Else
Computer Programming Practical 29
If Not button.Text.Equals("=") Then
' if the button is not "="
If Not isEqualClick Then
' if "=" is not clicked befor
num2 = Double.Parse(TextBox1.Text)
TextBox1.Text = Convert.ToString(calc(opr, num1, num2))
num2 = Double.Parse(TextBox1.Text)
opr = button.Text
isOprClick = True
isEqualClick = False
Else
isEqualClick = False
opr = button.Text
End If
Else
num2 = Double.Parse(TextBox1.Text)
TextBox1.Text = Convert.ToString(calc(opr, num1, num2))
num1 = Double.Parse(TextBox1.Text)
isOprClick = True
isEqualClick = True
End If
End If
End If
End Sub
' create a function to check if the button is a number or an operator
30 Computer Programming : Practical Book
Function isOperator(ByValbtn As Button) As Boolean
Dim btnText As String
btnText = btn.Text
If (btnText.Equals("+") Or btnText.Equals("-") Or btnText.Equals("/") Or
btnText.Equals("X") Or btnText.Equals("=")) Then
Return True
Else
Return False
End If
End Function
' create a function to do the calc
Function calc(ByVal op As String, ByVal n1 As Double, ByVal n2 As Double)
As Double
Dim result As Double
result = 0
Select Case op
Case "+"
result = n1 + n2
Case "-"
result = n1 - n2
Case "X"
result = n1 * n2
Case "/"
If n2 <> 0 Then
result = n1 / n2
Computer Programming Practical 31
End If
End Select
Return result
End Function
Private Sub ButtonReset_Click(sender As Object, e As EventArgs) Handles
ButtonReset.Click
num1 = 0
num2 = 0
opr = ""
oprClickCount = 0
isOprClick = False
isEqualClick = False
TextBox1.Text = "0"
End Sub
End Class
Use Toolbox with properties
In visual basic, you have to design the user interface. A visual basic interface consists
of objects that we place on screen in such a manner so that screen looks pretty and you
can work with those objects.
To design your user interface, we have to follow simply these steps-
1. At first, Create a form.
2. Choose the object you want to draw from the Toolbox.
3. Draw the object on the form.
So, create an object in visual basic, you have to use toolbox.
32 Computer Programming : Practical Book
Create DialogBoxes
Dialog Boxes in Windows Forms
Dialog boxes are used to interact with the user and retrieve information. In simple
terms, a dialog box is a form with its FormBorderStyle Enumeration property set
to FixedDialog. You can construct your own custom dialog boxes using the Windows
Forms Designer. Add controls such as Label, Textbox, and Button to customize
dialog boxes to your specific needs. The .NET Framework also includes predefined
dialog boxes (such as File Open, and message boxes), which you can adapt for your
own applications.
Creating Dialog Box at design time
Here is the step by step method to create a dialog box :
Add a form to your project by right-clicking the project in Solution Explorer, pointing
to Add, and then clicking Windows Form.
Computer Programming Practical 33
Right-click the form in Solution Explorer and choose Rename. Rename the form
"DialogBox.vb".
34 Computer Programming : Practical Book
In the Properties window, change the FormBorderStyle property to FixedDialog.
Customize the appearance of the form as needed.
Set the ControlBox, MinimizeBox, and MaximizeBox properties to false.
Dialog boxes do not usually include menu bars, window scroll bars, Minimize and
Maximize buttons, status bars, or sizable borders.
Computer Programming Practical 35
Customize event methods in the Code Editor.
Public Class DialogBox
Private Sub DialogBox_Load(ByVal sender As System.Object, ByVal e As Sy
stem.EventArgs) Handles MyBase.Load
End Sub
End Class
Create MDI Menu
MDI (Multiple Document Interface)
An application allows to work on multiple files and where the user needs to work with
several documents at one time.Such applications contain a parent form as container
form and other child forms.
To make a form as MDI Form set its IsMdiContainer property as true.
To define a parent form to a child form set MdiParent property.
To arrange the child forms, use LayoutMdi() method.
36 Computer Programming : Practical Book
To get reference of the current child form use ActiveMdiChild property.
To get reference of a control from the child form use its Controls collection.
Now, double click on the menustrip and colordialog control and create a menu in the
form. the form look like this the below forms.
Format menu look like this the below form.
Computer Programming Practical 37
Window menu show look like this the below form.
Now run the form and click on the new to create new form like this the below form.
38 Computer Programming : Practical Book
Now add this code.
Namespace MDIApp
Partial Public Class frmMDI
Inherits Form
Private i As Integer
Public Sub New()
InitializeComponent()
End Sub
Private Sub frmMDI_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim f As New frmChild()
f.MdiParent = Me
f.Show()
i=2
End Sub
Private Sub newToolStripMenuItem_Click(ByVal sender As Object, ByVal e
As EventArgs)
Dim f As New frmChild()
f.MdiParent = Me
f.Text
= "Documnent" &System.Math.Max(System.Threading.Interlocked.Increment(
i), i - 1)
f.Show()
End Sub
Private Sub cascadeToolStripMenuItem_Click(ByVal sender As Object, ByVal
e As EventArgs)
Me.LayoutMdi(MdiLayout.Cascade)
Computer Programming Practical 39
End Sub
Private Sub tileHorizontalToolStripMenuItem_Click(ByVal sender As Object,
ByVal e As EventArgs)
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub tileVerticalToolStripMenuItem_Click(ByVal sender As Object, By
Val e As EventArgs)
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
Private Sub arrangeIconsToolStripMenuItem_Click(ByVal sender As Object,
ByVal e As EventArgs)
Me.LayoutMdi(MdiLayout.ArrangeIcons)
End Sub
Private Sub colorToolStripMenuItem_Click(ByVal sender As Object, ByVal e
As EventArgs)
colorDialog1.ShowDialog()
Dim t As RichTextBox = DirectCast(Me.ActiveMdiChild.Controls("txtMain"),
RichTextBox)
t.SelectionColor = colorDialog1.Color
End Sub
End Class
End Namespace
40 Computer Programming : Practical Book
Unit - 9
Create Class, Objects, Constructor and Methods
class Box
{
//Private fields
private int length;
private int width;
private int heigth;
//Constructor
public Box(int length, int width, int height)
{
this.Length = length;
this.Width = width;
this.Heigth = height;
}
//Properties
public int Length
{
get { return length; }
set { length = value; }
}
public int Width
{
get { return width; }
Computer Programming Practical 41
set { width = value; }
}
public int Heigth
{
get { return heigth; }
set { heigth = value; }
}
//Method
public int Volume()
{
return this.Length * this.Width * this.Heigth;
}
}
Use build-in and user defined Component in Form.
Develop and use DLL.
Creating DLL File
Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then seelct
"Visual C#" -> "Class library".
42 Computer Programming : Practical Book
(I give it the name "Calculation".)
Step 2 - Change the class name ("class1.cs") to "calculate.cs".
Step 3 - In the calculate class, write methods for the addition and subtraction of two
integers (for example purposes).
Computer Programming Practical 43
Step 4 - Build the solution (F6). If the build is successful then you will see a
"calculation.dll" file in the "bin/debug" directory of your project.
We have created our DLL file. Now we will use it in another application.
Using DLL File
Step 1 - Open Visual Studio then select "File" -> "New" -> "Project..." then select
"Visual C#" -> "Windows Forms application".
44 Computer Programming : Practical Book
Step 2 - Design the form as in the following image:
Step 3 - Add a reference for the dll file, "calculation.dll", that we created earlier. Right-
click on the project and then click on "Add reference".
Step 4 - Select the DLL file and add it to the project.
Computer Programming Practical 45
After adding the file, you will see that the calculation namespace has been added (in
references) as in the following:
Step 5 - Add the namespace ("using calculation;") as in the following:
46 Computer Programming : Practical Book
Step 6
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Calculation;
namespace MiniCalculator
{
public partial class Form1 : Form
{
public Form1()
Computer Programming Practical 47
{
InitializeComponent();
}
calculate cal = new calculate();
//Addition Button click event
private void button1_Click(object sender, EventArgs e)
{
try
{
//storing the result in int i
int i = cal.Add(int.Parse(txtFirstNo.Text), int.Parse(txtSecNo.Text));
txtResult.Text = i.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Subtraction button click event
private void button2_Click(object sender, EventArgs e)
{
Try
{
//storing the result in int i
int i = cal.Sub(int.Parse(txtFirstNo.Text), int.Parse(txtSecNo.Text));
48 Computer Programming : Practical Book
txtResult.Text = i.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Develop a program to handle the exception
using System;
namespace ErrorHandlingApplication {
class DivNumbers {
int result;
DivNumbers() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
Computer Programming Practical 49
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
50 Computer Programming : Practical Book
Unit - 10
Develop Database Connection Program with Insert,
Update, Delete and Search Options.
Step 1
using System.Data.SqlClient;
You should use namespace given above to connect with SQL database.
Step2
You have to declare connection string outside the class.
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Inte
grated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
Step 3
Insert data in the database, as sgiven below.
if (txt_Name.Text != "" && txt_State.Text != "") {
cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,
@state)", con);
con.Open();
cmd.Parameters.AddWithValue("@name", txt_Name.Text);
cmd.Parameters.AddWithValue("@state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
Computer Programming Practical 51
DisplayData();
ClearData();
} else {
MessageBox.Show("Please Provide Details!");
}
Step 4
Updating record is given below.
if (txt_Name.Text != "" && txt_State.Text != "") {
cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state
where ID=@id", con);
con.Open();
cmd.Parameters.AddWithValue("@id", ID);
cmd.Parameters.AddWithValue("@name", txt_Name.Text);
cmd.Parameters.AddWithValue("@state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
} else {
MessageBox.Show("Please Select Record to Update");
}
52 Computer Programming : Practical Book
Step 5
Display record is shown below.
con.Open();
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("select * from tbl_Record", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
Step 6
Proceed, as shown below to delete the record.
if (ID != 0) {
cmd = new SqlCommand("delete tbl_Record where ID=@id", con);
con.Open();
cmd.Parameters.AddWithValue("@id", ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
} else {
MessageBox.Show("Please Select Record to Delete");
}
}
Generate the Report using Crystal Report.
First create an Employee Data Table in your SQL Database.
Now, follow the steps for creating a Crystal Report.
Computer Programming Practical 53
Step 1
Create a table in the database. Create an Employee table in the database.
Command
create table Employee
(
Emp_ID int identity(1,1) constraint PK_Emp primary key,
Emp_Name varchar(30),
Emp_Contact nchar(15),
Emp_Salary decimal(7,2)
)
Now insert employee data into the Employee Table.
Command
insert into Employee values ('Rakesh','9924194054','15000.22');
insert into Employee values ('Amit','9824194555','17000');
insert into Employee values ('Ketan','9824198245','14000');
insert into Employee values ('Ketan','9994198245','12000');
insert into Employee values ('Chirag','9824398245','10000');
insert into Employee values ('Naren','9824398005','10000');
Now Employee data has been inserted into the table.
Let's see it with a SQL Select Command Query in the SQL Database.
Command
Select * from Employee
54 Computer Programming : Practical Book
Step 2
Create a VIEW in your database to display employee data information.
Command
create view vw_Employee
as
Select Emp_ID,Emp_Name,Emp_Contact,Emp_Salary
from Employee
GO
Now, your Employee database view has been created.
Step 3
Go to Visual Studio.
Step 4
Go to the Solution Explorer and right-click on your project name and seelct Add ->
New Item.
Computer Programming Practical 55
Step 5 Add New Item-> Crystal Report.
56 Computer Programming : Practical Book
Step 6
Click the Ok Button.
Step 7
Choose the data source as in the following:
Click the Next Button.
Computer Programming Practical 57
Step 8
Select the data with OLEDB (ADO) as in the following:
Click the Next button to open a new dialog.
Click the Finish button and open a new dialog box. In this, select your new view.
58 Computer Programming : Practical Book
Step 9 : Select your view Employee view.
Step 10 : Select the fields to display in the report area as in the following.
And click the Finish button.
Computer Programming Practical 59
Step 11: Select the report format as in the following:
Click the Finish Button after selecting the format of the report.
Step 12 : Now finally display your report in this format.
60 Computer Programming : Practical Book
Step 13: Now add a new .aspx page to display the report as in the following:
And provide the name EmployeeDataInfo.aspx.
Step 14 : Now add a Crystal Report Viewer to EmployeeDataInfo.aspx as shown in
the following screeshot:
Computer Programming Practical 61
Step 15
Go to the aspx page code side as shown below:
Step 16
Write the report code in the .aspx.cs page as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace Network_Portal {
62 Computer Programming : Practical Book
public partial class EmployeeDataInfo: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
ReportDocument Report = new ReportDocument();
Report.Load(Server.MapPath("~/EmployeeData.rpt"));
Report.SetDatabaseLogon("sa", "sa123", "Rakesh-PC", "RakeshData");
CrystalReportViewer1.ReportSource = Report;
}
}
}
Computer Programming Practical 63
Step 17 : Finally run your report and display the Employee Information.
64 Computer Programming : Practical Book