You are on page 1of 87

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Introduction to Visual Studio .

NET: Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It can be used to develop console applications, Windows applications, Web applications, Mobile Applications, Windows / Web Services, etc using rich graphical user interface for all platforms supported by Microsoft. Visual Studio supports different programming languages by means of language services. The Most Preferred Built-in languages include VC++.NET, Visual Basic .NET, C#.NET. Support for other languages such as J#, M, Python, Perl and Ruby among others is available via language services installed separately. It also supports XML/XSLT, HTML/ XHTML, JavaScript and CSS.

What is .NET FrameWork ? The .NET Framework is a software environment responsible for the EXECUTION of code written in any of the languages supported by .NET (VB, C#, J#, VC++, etc). The .NET Framework must reside on the machine where the code is to be executed. .NET Framework, is installed as a part of Visual Studio .NET or can also be installed independently from Microsofts website. It is also in-built with Windows Operating systems. Prior to .Net: Microsoft has produced visual studio 6.0 (VB 6, C#, ASP) with classic ASP for developing web base application but there are several drawbacks in this project. Microsoft start a new project with code name Next Generation Windows Services (NGWS)

1 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 which was later named as .Net.

MICROSOFT .NET FRAMEWORK


Microsoft .Net framework is an integrated and managed environment for the development and execution of your code. The .Net Framework includes two main components: 1. The .Net Base Class Library. 2. The Common Language Runtime (CRL).

2 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

3 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 The .Net Base Class Library: The .Net base class library is a collection of object oriented classes and interfaces that provides object model and services for many complex programming tasks. The logical group of all these in-built classes and interfaces is called as a Namespace. i.e.: A Namespace is collection of classes. Some of the most important .Net Base Class Libraries are: System System.io System.data System.xml System.windows.form System.collections Etc. The Common Language Runtime (CRL): The Common Language Runtime (CLR) manages code at runtime. CLR as the name specifies, provides a common environment for programs written in different languages supported for .Net like VB, C#, VC++, J#, Perl, Python, etc. It offer INTEROPERABILITY between programs written in different languages i.e. An Application can have different modules written in different programming languages supported by .Net. CRL is a component divided in sub components which perform their own respective tasks. The components of CRL are: a. Common Type System (CTS): CTS is the major component of CRL. Its purpose is to provide data types conversion / consistency between different languages of .net to ensure interoperability. A subset of CTS is Common Language Specification (CLS) which also provides functionality to support interoperability. b. Just in time Compiler (JIT): When a .Net Program is compiled, an executable file is generated. This .exe file is in Microsoft Intermediate Language (MSIL). When the program is used / executed, then JIT compiler compiles only the required code, as it is visited in native (OS) form. This feature of .Net allows the programs to be Platform Independent.

4 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 As .Net has multiple languages, we require an appropriate language compiler specific for the language. All the compilers, after conversion of the source code, will generate the same type of code i.e. MSIL code which will be converted into machine code for execution. As all the .Net languages after compilation were generating the same type of code (IL). The code of one language can be consumed from any other .Net language. This Feature of .NET is Called Language Interoperability or language independency. c. Garbage Collection (GC): Garbage Collector is a background thread running with the application / CLR and is responsible for destroying all the unreferenced objects i.e. objects which are no longer in use. d. Class Loader: It is a Sub Component in CLR and is responsible for loading classes and other types as and when needed. e. Security Manager: Security Manager is a component of CLR. There are the types of security models supported in .Net: i. Code Access Security (CAS). ii. Role Based Security. iii. ASP.Net Web Application Security. The Security Manager decides whether or not a piece of code is allowed to run. It will prevent malicious code from entering your system and causing damage. f. Assemblies: An Assembly is a self describing collection of code, resource, and metadata. An Assembly manifest contains information about what is contained in the assembly like: i. Assemblys name and version number. ii. List of all the TYPES used by the program. iii. List of other assemblies, if any. iv. Security Details. Framework Versions Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released.

5 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 1.

MICROSOFT .NET FRAMEWORK

CLR

It is the core component of the framework which is responsible for converting the IL code into machine code. It is a set of libraries functionalities which have been provided common to all .Net languages. Win Forms are to be used in the development of graphical user interface (Windows application). It is used in the development of web applications using .Net languages.
(Windows Presentation Foundation ) : It is same of as Win Form used in the development of GUI applications but provides the support for graphics, animation, 2D, 3D image which was not provided under traditional Win Forms Technology)

BCL

Win Forms

ASP.Net

WPF

WCF

(Windows Communication Foundation): This is used in the development of distributed application. (Language Integrated Query): It is also used for interacting with databases similar to ADO.Net. ADO.Net entity Framework is an extension for traditional ADO.

LINQ

ADO.Net

6 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

The .NET Framework Version Number 1.0.3705.0 1.1.4322.573 2.0.50727.42 3.0.4506.30 3.5.21022.8

Version 1.0 1.1 2.0 3.0 3.5

Release Date Visual Studio 2002-02-13 2003-04-24 2005-11-07 2006-11-06 2007-11-19 Visual Studio 2008 Visual Studio .NET Visual Studio .NET 2003 Visual Studio 2005

Default in Windows

Windows Server 2003

Windows Vista, Windows Server 2008 Windows 7

7 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 2. DATA TYPES IN .NET 1. Value Type 2. Reference Type 1. VALUE TYPE: i. Integer Types: Data Type Byte Sbyte Short Ushort Integer Uinteger Long Ulong ii. Floating Types: Data Types Single Double Decimal Size 4 8 16 Size 1 1 2 2 4 4 8 8

iii. Other Data Types: Data Types Char Boolean Date iv. Reference Types: Eg: Object, Strings, Arrays, etc. Size 2 2 8

8 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

9 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

3. OPERATORS
Arithmetic Operators: Operator ^ * \ / Mod + Comparison Operators: Operator < > <= >= = <> exp1 < exp2 exp1 > exp2 Exp1 <= exp2 Exp1 >= exp2 Exp1 = exp2 Exp1 <> exp2 Usage Function Power of an exponent Multiplication Divide two numbers and returns integer Divide two numbers and returns float Remainder of the equation Addition subtraction

Assignment Operators: Operator = *= /= \= += -= &= Logical Operators: AND 10 VB.Net Variable = value Multiplication and assignment Div & assign (float) Div & assign (integer) Add & assign Sub & assign Concatenates a string exp to a string variable Usage

www.sfkinfotech.com Sarfaraz Khan - 9763987372 OR NOT

11 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 4. STATEMENTS If Demo Output

Select Demo Output

For Demo Output

12 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

13 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Public Class Frm_Demo_if Dim total As Integer Dim per As Single Dim result As String Private Sub btn_result_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_result.Click total = CInt(txtMarks1.Text) + CInt(txtMarks2.Text) + CInt(txtMarks3.Text) per = (total * 100) / 300 If per < 35 Then result = "FAIL" Else result = "PASS" End If Msgbox("Total : " + CStr(total) + vbCrLf + "Per : " + CStr(per) + vbCrLf + "Result : " + result) End Sub End Class Public Class frm_for_table Dim n As Integer Dim str As String Dim i As Integer Private Sub btn_table_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_table.Click str = "" n = CInt(txttable.Text) For i = 1 To 10 str &= CStr(n) + " X " + CStr(i) + " = " + CStr(n * i) + vbCrLf Next MsgBox(str) End Sub End Class Public Class frm_demo_select

Private Sub Btn_Percentage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Percentage.Click Select Case (txtgrade.Text.ToUpper) Case "A" MsgBox("The Percentage is above 75%") Case "B" MsgBox("The Percentage is between 65 % AND 75%") Case "C" MsgBox("The Percentage is Between 40% & 65%") Case "D" MsgBox("The Percentage is below 40%") Case Else MsgBox("Invalid char...please enter A,B,C or D") End Select End Sub End Class

14 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 5. STRUCTURE DEMO OUTPUT

Public Class frm_structure_demo Public Structure stud Dim n As String Dim p As Integer Dim c As Integer Dim m As Integer End Structure Dim s1 As stud Private Sub frm_structure_demo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load txtphy.Enabled = False txtchem.Enabled = False txtmaths.Enabled = False txtname.Enabled = False End Sub Private Sub btn_new_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_new.Click txtphy.Enabled = True txtchem.Enabled = True

txtmaths.Enabled = True txtname.Enabled = True txtphy.Clear() txtchem.Clear() txtmaths.Clear() txtname.Clear() txtname.Focus() End Sub Private Sub btn_getresult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_getresult.Click Dim tot As Integer Dim per As Single s1.n = txtname.Text s1.p = CInt(txtphy.Text) s1.c = CInt(txtchem.Text) s1.m = CInt(txtmaths.Text) tot = s1.c + s1.p + s1.m per = (tot * 100) / 300 MsgBox("Name = " + s1.n + vbCrLf + "Total = " + tot.ToString + vbCrLf + "Per = " + per.ToString) End Sub End Class

15 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

16 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 6. ARRAY DEMO OUTPUT

Public Class frm_array_demo Dim s(5) As String Dim str As String Dim a As String Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click s(0) s(1) s(2) s(3) s(4) s(5) = = = = = = txtname1.Text txtname2.Text txtname3.Text txtname4.Text txtname5.Text txtname6.Text

Private Sub btnsort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsort.Click Array.Sort(s) str = "" For Each a In s str &= a + vbCrLf Next MsgBox(str, , "Sorted Member of The Array") End Sub Private Sub btnreverse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreverse.Click Array.Reverse(s) str = "" For Each a In s str &= a + vbCrLf Next MsgBox(str, , "Reversed Member of The Array") End Sub End Class

MsgBox("The Length of Array S is " + s.Length.ToString) For Each a In s str &= a + vbCrLf Next MsgBox(str, , "Member of The Array") End Sub

17 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 7. DYNAMIC ARRAY OUTPUT

Public Class frm_dynamic_array Dim s() As String Dim i As Integer = 0 Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click ReDim s(CInt(TxtNumber.Text)) End Sub Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click For i = 0 To s.Length - 1 s(i) = InputBox("Enter name " + (i + 1).ToString) Next End Sub

Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click Dim str As String = "" Dim i As Integer = 0 For i = 0 To s.Length - 1 str &= s(i) + vbCrLf Next MsgBox(str) End Sub End Class

18 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 8. CALL BY VALUE & CALL BY REFERENCE

Demo of Call by Val & Call by Reference

Public Class Form1 Dim l As Integer Dim m As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click l = CInt(TextBox1.Text) m = CInt(TextBox2.Text) func_add(l, m) TextBox1.Text = l TextBox2.Text = m

End Sub Public Sub func_add(ByVal a As Integer, ByRef b As Integer) a += 1 b += 1 End Sub

19 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Class

20 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 9. EXCEPTION HANDLING

Exceptions are runtime error cause due to a logical error, S/W error or limitation of the hardware.

In .Net, every exception is an object of type system.exception or any of its sub classes.

When the integrity on an object is violated, an exception is raised. Exception Handling is done by providing try catch blocks. If an exception is thrown and is unhandled is an inner block then it is automatically thrown to its outer block. If an exception is unhandled, then the CLR terminated the program abruptly.

For one Try block, we can have multiple catch blocks, each for a specific exception.

Finally block may be written to execute all the necessary code to execute before exiting the program, in case of exception or no exception.

21 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class txtvalue2 Dim a As Integer Dim b As Integer Dim c As Integer

Private Sub btnDivide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDivide.Click Try a = CInt(txtvalue1.Text) b = CInt(TextBox2.Text) c=a/b MsgBox(c.ToString) Catch ex As InvalidCastException MsgBox(ex.Message & vbCrLf & "Enter Valid Data") Catch ex As Exception MsgBox(ex.Message) Finally txtvalue1.Text = "" TextBox2.Text = "" txtvalue1.Focus() End Try End Sub End Class

22 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

VB.NET OOPs Guide


Object Oriented Programming Structure (OOPS)

The programming in which data will be logically represented in the form of a class and physically represented in the form of an object is called as object oriented programming. OOPS has following important features:

1. Class:According to oops data must be represent in the form of class. A class can contain variables for storing the data and function to specify various operations that can perform on data. Class doesnt occupy any memory space hence its only logical representation of data. Object oriented programming features are taken from real life. In a real life a plan will be drawn before constructing any object the same is implemented in oops with the form of class. A class is like a plan or blueprint for the data of your program.

2. Data Encapsulation & Abstraction:


A Class can contain variables for storing the data and functions to specify various operations that can be performed on data. This process of wrapping of data and functions that operate on that data as a single unit in the form of class is called as data encapsulation. Advantage of encapsulation is hiding the implementation detail of class. In real life if you take CPU of system , it is encapsulation of various component like motherboard, Ram, Hard Disk and Other hardware to use the CPU no need to have the knowledge how exactly all this component are working internally the same is implemented in oops in the form of data encapsulation. Abstraction is the process hiding details of class when member of a class are declared as private when it is not possible to access them from outside the class.

23 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Advantages of this are security in the real life all the components of CPU are enclosed in a cabinet to protect them from the dust same is implemented in oops in the form of abstraction.

Object and Instance: Object with keyword New Stack Heap

Permanent Memory

A class is a only a logical representation of data hence to work with the data represented by the class you must declare variable for the class, which is called as an object when an object is declared using the keyword new then memory will be allocated for the members of the class within the heap memory area which is called as Instance & its address will be stored in the object in stack. When an object is created without using the keyword new then instance will not be created and object in stack will contain Null. In this case its not possible to access the members of the class by using that object because the object contains Null.

Constructor
1. A constructor is a special method present under every class responsible for initializing the variable of the class. 2. A constructor is a non value returning method and will have the same name of class. 3. A constructor is mandatory under every class is the class has to execute. Note: where out C# compiler compiles the program it verifies whether the class contains the constructor in it or not. If not present the class can not execute so on behalf of the programmer the compiler takes the responsibility in defining a constructor under the program so that class can execute.

24 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 4. Constructor is special method in the class that will be automatically invoked while an instance is created for the class its main purpose is to initialize the fields available in the class while instance is created. But you can write any code that needs to be executed while an instance is created. When you are not creating constructor in the class than compiler will automatically create a default constructor that will initialize fields in the class to the default value based data type. To create a constructor in the class in the vb.net create a sub procedure in the class with the name new.

Type of constructor:

1. Default constructor: - A constructor without any parameters is called as a default constructor. A drawback of default constructor is any no of instances you create for the class, all the instances will be unitized to same value and its not possible to initialize each instance of the class to different values. 2. Parameterized Constructor: A constructor with at least one parameter is called as parameterized constructor advantage of this is each instance of the class can be initialized to deferent value. 3. Copy constructor: In parameterized constructor with a parameter of same class type is called as copy constructor. Purpose of copy constructor is to copy the values of an existence instance to the new instance. 4. Shared Constructor: You can also declare a constructor as shared but a shared constructor will be invoked only once for any once for any no of instances created for the class. A shared constructor will be invoked in any of the following situation.

1) When first instance is created for the class. 2) When you referred to a shared member in the class for the first time. Shared constructor is used to write the code thats need to be executed only once.

5. Private Constructor: Constructor can also be created as private but when there is at least ne private

25 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 constructor available in the class create an instance for the class will not be possible. Purpose of privat3e constructor is to restrict the class form being instantiate when the class contains every member as shared.

Point Related to Constructor 1. A class can have any no of constructors in the class provided they satisfy method overloading rule. 2. A class can have only one shared constructor or and shared constructed cant parameterized. 3. Constructor must be a sub-procedure and cant be a function procedure.

Destructor
Destructor is a special method in the class that will be automatically invoked while an instance of the class is destroyed. Destructor is used to write the code that needs to be executed while an instance of the class is destroyed when you are not creating a destructor in the class than compiler will not destructor automatically, to create a destructor within a class in VB.net , create sub-procedure with the name finalize that has following syntax.

Protected overrides sub finalize <Statement> End sub

By default every class in .Net is inherited from a class called as Object even your are not specifying to inherit explicitly within this object class the finalize method is overridable method and declared with the access modifier protected. Creating finalize method your calss is nothing but the overriding the finalize method of base class hence it must be declared with the keyword overrides. To make the destructor available only within the same class and its derived classes but not from outside the class it must be declared as protected.

26 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 In .Net object will not be destroyed immediately after their lifetime is expired. And they will be destroyed only when garbage collector performs garbage collection. Garbage collector will perform garbage collection only in the following two situations. 1. When there is not enough memory to create a new object. 2. When your application comes to an end.

When you dont want to wait until the garbage collector performs garbage collection then you can force the garbage collector to perform garbage collection by calling collect method of GC class. But this is not recommended as if affects the performance of the application.

Point about destructor: 1. A Class can have only one destructor. 2. Destructor must be a sub procedure cant possible to create it as function. 3. Destructor cannot be parameterized. 4. Destructor cannot be shared.

10. OOPS Classes, Objects, Constructors & Destructors

Public Class Accounts


Private accno As Integer Private acc_name As String Private bal As Integer

27 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 'Constructor Public Sub New() MsgBox("Objected Created") End Sub 'Public Method to Populate Above Three Private Varaible Public Sub setdata(ByVal a As Integer, ByVal b As String, ByVal c As Integer) Me.accno = a Me.acc_name = b Me.bal = c End Sub 'Public Method to Display msgbox as output Public Sub getdata() MsgBox(Me.accno.ToString + vbNewLine + Me.acc_name + vbNewLine + Me.bal.ToString) End Sub 'Destructor Protected Overrides Sub finalize() MsgBox("Objected Destroyed") End Sub

End Class Public Class Frm_OOP_Demo_1


'Declaring the Obj. of Class Account Dim obj As Accounts

Private Sub btn_Create_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Create.Click


'Initializing The Object obj on class Accounts obj = New Accounts

End Sub Private Sub btn_set_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_set.Click
'Sending the Values from textboxs to Accounts Class Through Method SetData obj.setdata(CInt(txtaccno.Text), txtname.Text, CInt(txtbalance.Text))

End Sub Private Sub btn_get_Click(ByVal sender As System.Object, ByVal e As 28 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 System.EventArgs) Handles btn_get.Click 'Calling the Method Getdata to view the Output obj.getdata() End Sub Private Sub btn_destroy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_destroy.Click 'Calling The Destructor obj = Nothing End Sub

End Class

29 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

11. OOPS PROPERTIES

30 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Public Class Accounts Private Integer Private Private Private Shared accno As = 0 accname As String bal As Integer minbal As Integer Public WriteOnly Property pro_minbal() Set(ByVal value) Me.minbal = value End Set End Property Public ReadOnly Property pro_accno() Get Return accno End Get End Property Public Sub desposit(ByVal a As Integer) Me.bal += a End Sub Public Sub withdraw(ByVal a As Integer) If Me.bal - a < Me.minbal Then MsgBox("Insufficient Balance") Else Me.bal -= a End If End Sub Protected Overrides Sub finalize() MsgBox("Objects Destroyed") End Sub End Property

Public Sub New() MsgBox("Object Created") accno += 1 End Sub Public Property pro_accname() Get Return Me.accname End Get Set(ByVal value) Me.accname = value End Set End Property Public Property pro_bal() Get Return Me.bal End Get Set(ByVal value) Me.bal = value End Set

End Class

Public Class Frm_OOP_Demo


Dim acc1 As Accounts Private Sub btn_create_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_create.Click acc1 = New Accounts txtno.Text = acc1.pro_accno End Sub 31 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btn_set_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_set.Click acc1.pro_accname = txtname.Text acc1.pro_bal = CInt(txtbal.Text) acc1.pro_minbal = CInt(txtminbal.Text) End Sub Private Sub btn_get_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_get.Click MsgBox(acc1.pro_accno.ToString + vbCrLf + acc1.pro_accname + vbCrLf + acc1.pro_bal.ToString) End Sub Private Sub btn_deposit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_deposit.Click acc1.desposit(CInt(txtamt.Text)) txtbal.Text = acc1.pro_bal End Sub Private Sub btn_withdraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_withdraw.Click acc1.withdraw(CInt(txtamt.Text)) txtbal.Text = acc1.pro_bal End Sub

End Class

32 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

12. OOPS INHERITANCE 12.1 Inheritance:


While creating a new class if it requires same members as existing class then instead of re-creating those members you can create the new class from an existing class. This process of creating a new class from an existing class is called as inheritance.

Advantage of inheritance is code reusability. During inheritance the class that is inherited is called as base class and the class that does the inheritance is called as derived class or child class and every non private member of the base class will become the member of derive class with the same access modifier as in base class. To perform inheritance, you have to use the keyword inherits and its has the following syntax.

[Access modifier] class<class name> inherits <BaseClass_name> <Member> End class Inheritance allows you to create a new class that retains all the members and Functionalities of a previously defined class. This feature of OOP allows code reusability.

Public 33 public public public

Class stud_info sno As Integer sname As String address As String

Public Class mba Inherits stud_info VB.Net Public fin As Integer Public hr As Integer Public mkt As Integer

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Public Class frm_inheritance_Demo Private Sub btnNewMBA_Click Dim s1 As mca Dim s2 As mba Private Sub btnNewMCA_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewMCA.Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Click

s2 = New mba Label4.Text = "FIN" Label5.Text = "HR" Label6.Text = "MKT" txtsno.Focus() End Sub PrivateSub btnMBAsave_Click (ByVal sender As System.Object, ByVal e

s1 = New mca Label4.Text = "OS" Label5.Text = "DBMS" Label6.Text = "C" txtsno.Focus() End Sub

As System.EventArgs) Handles btnMBAsave.Click

Private Sub btnMCAsave_Click 'saving info to MBA obj


(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMCAsave.Click

'saving info to MCA obj s1.sno = CInt(txtsno.Text) s1.sname = txtsname.Text s1.address = txtaddress.Text s1.os = CInt(txtmark1.Text) s1.dbms = CInt(txtmark2.Text) s1.c = CInt(txtmark3.Text) End Sub

s2.sno = CInt(txtsno.Text) s2.sname = txtsname.Text s2.address = txtaddress.Text s2.fin = CInt(txtmark1.Text) s2.hr = CInt(txtmark2.Text) s2.mkt = CInt(txtmark3.Text) End Sub
Private Sub

btnMBAResult_Click

(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Click

Private Sub btnMCAResult_Click s2.result()


(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMCAResult.Click

s1.result() End Sub

End Sub End Class

34 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Type of Inheritance 1. Single Inheritance: The inheritance in which a single derived class is created from a single base class is called as single inheritance.

2. Hierarchical Inheritance: - The inheritance in which more than one derived class is created from a single base class is called as hierarchical inheritance.

3. Multilevel inheritance: - The inheritance in which a derived class is created from another derived class is called as multilevel inheritance.

4. Hybrid Inheritance: - The inheritance i.e. the combination of hierarchical and multilevel inheritances is called as hybrid inheritance.

35 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

5. Multiple Inheritances: - The inheritance in which a single derived class is created from multiple base classes is called as multiple inheritances.

Note: multiple inheritances not supported by .net using classes and its supported using interface. During multiple inheritance if more than one base class contain members with same signature then derived class will get more than one member with same signature, which is not actually possible overcome this problem c++ use virtual base class concept that internal requires pointers but .net doesnt support pointers and hence if cannot provide virtual base class concept and hence multiple inheritance was not supports.

36 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

13. OOPS MustInherit Class & Method Overriding


MustInherit (Abstract Classes): when a Class is Defined as Mustinherit, then an object cannot be created directly on that class, and it must have a derived class through which its member will be accessed. Method Overriding: a. Notoverridable (Default): A Method of the base class, which cannot be overridden in the derived classes. b. Overridable: A Method of the base class, that MAY have a new implementation in the derived class. c. Mustoverride: A Method of the base class, which MUST have a new implementation in the derived class. This method can only be declared in a Mustinherit class. d. Override: A Method of the base class, which overrides the method of its base class.

37 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public MustInherit Class stud_info Protected sno As Integer Protected sname As String Protected address As String Public MustOverride Sub marks
(a as integer, b as string, c as string, m1 as integer, m2 as integer, m3 as integer)

Public Class mba Inherits stud_info private fin,hr,mkt As Integer Public Overrides Sub marks
(a as integer,b as string,c as string,m1 as integer,m2 as integer,m3 as integer)

Public MustOverride sub result() End Class Public Class mca Inherits stud_info private os,dbnms,c As Integer Public Overrides Sub marks
(a as integer, b as string, c as string, m1 as integer, m2 as integer, m3 as integer)

Me.sno = a Me.sname = b Me.address = c Me.fin = m1 Me.hr = m2 Me.mkt = m3 End sub Public Overrides Sub result() Dim tot As Integer Dim per As single Dim str,res As String tot = me.fin + me.hr + me.mkt per = CDec((tot * 100) / 300) If per < 50 Then res = "FAIL" Else res = "PASS" End If str &= Me.sno.ToString + vbCrLf str &= Me.sname + vbCrLf VB.Net str &= Me.address + vbCrLf str &= tot.ToString + vbCrLf

Me.sno = a Me.sname = b Me.address = c Me.os = m1 Me.dbms = m2 Me.c = m3 End sub Public Overrides Sub result() Dim tot As Integer Dim per As single 38 str,res As String Dim tot = me.os + me.dbms + me.c per = CDec((tot * 100) / 300) If per < 40 Then

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Public Class frm_inheritance_Demo Private Sub btnNewMBA_Click Dim s1 As mca Dim s2 As mba Private Sub btnNewMCA_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewMCA.Click (ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles Click

s2 = New mba Label4.Text = "FIN" Label5.Text = "HR" Label6.Text = "MKT" txtsno.Focus() End Sub Private Sub btnMBAsave_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Click

s1 = New mca Label4.Text = "OS" Label5.Text = "DBMS" Label6.Text = "C" txtsno.Focus() End Sub Private Sub btnMCAsave_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMCAsave.Click

'saving info to MCA obj S1.marks(CInt(txtsno.Text), txtsname.Text, txtaddress.Text, CInt(txtmark1.Text), CInt(txtmark2.Text), CInt(txtmark3.Text)) End Sub Private Sub btnMCAResult_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMCAResult.Click

'saving info to MBA obj S2.marks(CInt(txtsno.Text), txtsname.Text, txtaddress.Text, CInt(txtmark1.Text), CInt(txtmark2.Text), CInt(txtmark3.Text)) End Sub Private Sub btnMBAResult_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Click

s2.result() End Sub End Class

s1.result() End Sub

39 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

14. OOPS - INTERFACE


An interface is nothing but the user defined data type that can contain only declarations and not definition. Main purpose of interface is to provide contract for the class must provide definition for a set of members. To create an interface use the keyword interface that has the following syntax.

[Access modifier] interface <interface > <interface name> <Interface members> End interface

While creating an interface, consider the following points. 1) An Interface can contain only declarations and its not possible to define any member in the interface. 2) Interface cant contain field. 3) It is not possible to specify access modifier for the members of an interface and every member in interface is public by default. 4) It is not possible to declare the member of an interface as shared.

To implement interfaces in a class use the keyword implement and it has the following syntax [access modifier]classname :implements <interface1><interface2>, <member> End class

One class can implement any no of interfaces and one interface can be implemented by any no of classes. But when a class implements an interface them it must provide the definition for every member in the interface otherwise it will be a compilation error. There may be a situation where more than one interface contain a member with same signature and those interfaces are implemented in the same class. In this case to resolve the ambiguity, simple solution is rename one of those

40 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 method of class while they are defined. Even the method was rename compiler will identify to which method which interface the definition belongs based on implementa statement at the end of that method of declaration within the class. An interface is a collection of related methods and properties without implementation. An interface is a point of contact with an object. An interface is equal to a Mustinherit Class with all members declared as Mustoverride. We can implements multiple inheritance and multilevel inheritance with the help of interfaces.

41 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Public Interface Istud Sub stud_info(ByVal n As String, ByVal a As Integer, ByVal b As Integer, ByVal c As Integer) Sub result() End Interface Public Class mca Implements Istud Private Private Private Private sname As String os As Integer dbms As Integer c As Integer Public Class mba Implements Istud Private Private Private Private sname As String fin As Integer hr As Integer mkt As Integer

Public Sub stud_info


(ByVal n As String, ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)

Implements Istud.stud_info Me.sname = n Me.fin = a Me.hr = b Me.mkt = c End Sub Public Sub result() Implements Istud.result Dim Dim Dim Dim tot per str res As As As As Integer Decimal String = "" String = "PASS"

Public Sub stud_info (ByVal n As String, ByVal a

As Integer, ByVal b As Integer, ByVal c As Integer)

Implements Istud.stud_info Me.sname = n Me.os = a Me.dbms = b Me.c = c End Sub Public Sub result() Implements Istud.result Dim Dim Dim Dim tot per str res As As As As Integer Decimal String = "" String = "PASS"

tot = Me.fin + Me.hr + Me.mkt per = CDec((tot * 100) / 300) If per < 50 Then res = "FAIL" End If str str str str &= &= &= &= Me.sname + vbCrLf tot.ToString + vbCrLf per.ToString + vbCrLf res

tot = Me.os + Me.dbms + Me.c per = CDec((tot * 100) / 300) If per < 40 Then res = "FAIL" End If str str str str &= &= &= &= Me.sname + vbCrLf tot.ToString + vbCrLf per.ToString + vbCrLf res

MsgBox(str) End Sub End Class

MsgBox(str) End Sub End Class

42 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Public Class frm_Interface_Demo Private Sub btnNewMBA_Click (ByVal sender As System.Object, Dim s As Istud ByVal e As System.EventArgs) Handles Private Sub btnNewMCA_Click(ByVal btnNewMBA.Click sender As System.Object, ByVal e As System.EventArgs) Handles s = New mba btnNewMCA.Click End Sub s = New mca Private Sub btnMBASave_Click End Sub (ByVal sender As System.Object, ByVal e As System.EventArgs) Private Sub btnMCASave_Click Handles btnMBASave.Click (ByVal sender As System.Object, ByVal e As System.EventArgs) s.stud_info(txtname.Text, Handles btnMCASave.Click CInt(txtmarks1.Text), CInt(txtmarks2.Text), s.stud_info(txtname.Text, CInt(txtmarks3.Text)) CInt(txtmarks1.Text), CInt(txtmarks2.Text), End Sub CInt(txtmarks3.Text)) Private Sub btnMBAResult_Click End Sub (ByVal sender As System.Object, ByVal e As System.EventArgs) Private Sub btnMCAResult_Click Handles btnMBAResult.Click (ByVal sender As System.Object, ByVal e As System.EventArgs) s.result() Handles btnMCAResult.Click End Sub s.result() End Class End Sub

43 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

15. OOPS - METHOD OVERLOADING

Methods are procedures that contain application logic. Methods in VB.NET can be either:

1. Sub Procedures 2. Functions

A Method created with sub does not return a value. A Method create with function must return a value.

Parameters to methods are declared as Byval by default, but it may also be ByRef.

44 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Public Class cal Public Sub welcome() MsgBox("Welcome") End Sub Public Function add(ByVal a As Integer, ByVal b As Integer) As Integer Return a + b End Function Public Function add(ByVal a As Decimal, ByVal b As Decimal) As Decimal Return a + b End Function Public Function add(ByVal a As String, ByVal b As String) As String Return a + b End Function End Clas ElseIf rdostring.Checked = True Then s = obj.add(txtvalue1.Text, txtvalue2.Text) MsgBox(s) Else MsgBox("Please Select One Option") End If End Sub End Class obj = New cal obj.welcome() If rdointerger.Checked = True Then i = Obj.add(CInt(txtvalue1.Text), CInt(txtvalue2.Text)) MsgBox(i.ToString) ElseIf rdodecimal.Checked = True Then d = obj.add(CDec(txtvalue1.Text), CDec(txtvalue2.Text)) MsgBox(d.ToString) Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click Public Class frm_func_overloading Dim Dim Dim Dim obj As cal i As Integer d As Decimal s As String

45 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

16. OOP - Multiple Inheritance Demo

Public Class stud


Protected sno As Integer Protected sname As String Protected address As String

Public Class mca Inherits stud Implements Isem_1


Dim tot As Integer Dim per As Single Dim res As String Dim str As String Public Sub marks(ByVal c As Integer, ByVal os As Integer, ByVal dbms As Integer) Implements Isem_1.marks tot = c + os + dbms per = CDec((tot * 100) / 300) If per < 40 Then res = "FAIL" Else res = "PASS" End If End Sub Public Sub result() Implements Isem_1.result str = "" str &= Me.sno.ToString + vbNewLine str &= Me.sname + vbNewLine str &= Me.address + vbNewLine str &= tot.ToString + vbNewLine str &= per.ToString + vbNewLine str &= res MsgBox(str, , "MCA I-Sem Result")

Public Sub set_data


(ByVal a As Integer, ByVal b As String, ByVal c As String) Me.sno = a Me.sname = b Me.address = c End Sub End Class

Public Interface Isem_1


Sub marks(ByVal c As Integer, ByVal os As Integer, ByVal dbms As Integer) Sub result() End Interface

46 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 End Sub End Class

Public Class Frm_Multiple_Inheritence


Dim obj As mca

Private Sub btn_new_Click


(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_new.Click obj = New mca

End Sub Private Sub btn_save_Click


(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click obj.set_data(CInt(TextBox1.Text), TextBox2.Text, TextBox3.Text) obj.marks(CInt(TextBox4.Text), CInt(TextBox5.Text), CInt(TextBox6.Text))

End Sub Private Sub btn_result_Click


(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_result.Click obj.result()

End Sub End Class

47 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

VB.NET User Interface Guide


15. DESIGNING & DEVELOPING USER INTERFACE
1.

FORM

Properties: Name, Text, Backcolor, BackgroundImage, Cursor, Font, Forecolor, Opacity, Startupposition, Windowstate, etc Events: Load, Activated, Deactivate, Click, DoubleClick, FormClosing, Formclosed, Keypress, MouseEnter, MouseLeave, etc Methods: Close, CentertoScreen, resettext, show, showdialog, hide, etc
2.

LABEL

Properties Name, Autosize, Backcolor, Borderstyle, Font, Forecolor, Image, Text, Visible, Etc. Events: Click, Leave, etc. Methods Focus, hide, show, resettext, tostring
3.

TEXT BOX:

Properties: Name, Autosize, AutoCompleteCustomSource, AutoCompleteMode, AutoCompleteSource, Backcolor, Borderstyle, Font, Forecolor, Multiline, Readonly, PasswordChar, text, etc Events: Click, Enter, Leave, Keypress, Keydown, Keyup, TextChanged, etc Methods: Clear, Copy, Cut, Paste, Focus, Hide, Show, etc
4.

COMMAND BUTTON

Properties: Name, Backcolor, BackgroundImage, FlatStyle, Font, ForeColor, Text, Enabled, Visible. 48 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Events: Click, Enter, Leave, Etc Methods: Focus, Hide, Show, etc 5. COMBO BOX Properties: Name, Font, Forecolor, Font, Items, Text, Visible, etc Events SelectedIndexChanged, SelectValueChanged, Keydown, Keyup, KeyPress, Enter, Leave. Methods Hide, Show, Items -> add, addrange, insert, clear, remove, removeat, etc
6.

LIST BOX

Properties: Name, Font, Forecolor, Font, Items, Text, Visible, etc Events SelectedIndexChanged, SelectValueChanged, Keydown, Keyup, KeyPress, Enter, Leave. Methods Hide, Show, focus, ITEMS -> add, addrange, insert, clear, remove, etc

7.

CHECK BOX

& 8.

RADIO BUTTON

Properties Name, checkalign, checked, checkstate, font, forecolor, text, visible, etc Events Checkedchange, checkedstatechanged, click, etc Methods Show, hide, focus, etc

9.

MONTH CALENDAR

Properties Name, AnnuallyBoldedDates, MonthlyBoldedDates, BoldedDates, Backcolor, ForeColor, Font, FirstDayofweek, maxdate, mindate, Showtoday, titlebackcolor, titleforecolor, etc

49 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Events Datechanged, dateselected, etc Methods Addboldeddates, hide, show, setdate, focus, etc

10.

DATE TIME PICKER

Properties Name, calenderforecolor, calenderfont, calendarmonthbackground, calendartitlecolor, etc Events Valuechanged, etc Methods Hide, show, focus, VALUE -> addseconds, addminutes, addhour, adddays, addmonths, addyears, isleapyear, etc

11.

PICTURE BOX:

Properties Name, image, errorimage, sizemode, backcolor, backgroundimage, borderstyle, etc Events Click, layout Methods Show,hide,focus, IMAGE -> Fromfile, Save, etc 12. Timer Control: Properties: Name, Enable, Interval (1000 = 1 sec) Events: Tick Methods: Start, Stop

50 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Example: Private Sub Timer1_Tick Label1.Text = DateTime.Now.Date Label2.Text=DateTime.Now.ToLongTimeString.ToString End Sub Private Sub Button1_Click Timer1.Start() End Sub Private Sub Button2_Click Timer1.Stop() End Sub 13. Progress Bar: Property: Name, ForeColor, Maximum, Minimum, value, style, enable Events: -Methods: -Example: Private Sub Timer1_Tick If pgbar.Value < 100 Then pgbar.Value += 10 Else pgbar.Value = 0 End If End Sub

Tab Control: Property: Events: -Methods: -TabPages

51 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

16. USER INTERFACE DEMO

Public Class frm_Student_Info


Dim Dim Dim Dim Dim Dim Dim Dim Dim fees As Integer name As String = "" mob As Long str As String time As String q As String br As String doe As Date nq As String

cmbbranch.Items.AddRange(New Object() {"Select", "Cidco", "Osmanpura", "City Chowck"}) cmbbranch.SelectedIndex = 0 lstqualification.Items .AddRange(New Object() {"MCA", "Msc", "MCM", "Others"})

Private Sub frm_Student_Info_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


'ComboBox1.Items.Add("CIDCO")
'ComboBox1.Items.Insert(0, "OSMANPURA")

End Sub

52 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372


'ListBox1.Items.Add("MCA") 'ListBox1.Items.Insert(0, "MSc")

Private Sub lstqualification_SelectedIn dexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstqualification.SelectedInd exChanged
If lstqualification.SelectedIndex = 3 Then nq = InputBox ("Enter Your qualification") End If

If chkmsnet.Checked = True Then fees += 3000 End If If rdomorning.Checked = True Then time = "Morning Batch" ElseIf rdoafternoon.Checked = True Then time = "Afternoon Batch" ElseIf rdoevening.Checked = True Then time = "Evening Batch" ElseIf rdofasttrack.Checked = True Then time = "Fast Track Batch" End If br = cmbbranch.SelectedItem.ToString q=stqualification.SelectedItem.T oString doe = dtpbatch.Value str str str str str str str str &= &= &= &= &= &= &= &= name + vbCrLf mob.ToString + vbCrLf fees.ToString() + vbCrLf time + vbCrLf q + vbCrLf br + vbCrLf doe.Date + vbCrLf MonthCalendar1.TodayDate

End Sub Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
name = txtname.Text mob=Convert.ToUInt64(txtmobile.Text) fees = 0 str = "" If chkjava.Checked = True Then fees += 3000 End If If chkccpp.Checked = True Then fees += 1000 End If If chkdba.Checked = True Then fees += 3000 End If

If lstqualification.SelectedIndex = 3 Then str &= nq End If MsgBox(str)

End Sub End Class

53 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

54 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

17. MDI DEMO

Public Class Form1 Dim frm2 As Form2 Private Sub LOGINToolStripMenuItem_Click frm2 = New Form2 frm2.MdiParent = Me frm2.Show() End Sub Private Sub EXITToolStripMenuItem_Click If MsgBox("Do You Wish To Exit", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then Me.Close() End If End Sub 55 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Class Public Class Form2 Dim frm3 As Form3 Private Sub Button1_Click frm3 = New Form3 frm3.obj = New global_class frm3.obj.pro_username = TextBox1.Text frm3.MdiParent = Me.MdiParent frm3.Show() Me.Close() End Sub End Class Public Class Form3 Public obj As global_class Private Sub Form3_Load Label1.Text = "Hello " + obj.pro_username + " Welcome to SFK INFOTECH PVt. LTD." End Sub End Class Public Class global_class Private username As String Public Property pro_username() Get Return Me.username End Get Set(ByVal value) Me.username = value End Set 56 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 End Property End Class

57 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Dialog Control

Public Class Frm_Dialog_Demo Private Sub btn_font_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_font.Click If fd.ShowDialog = Windows.Forms.DialogResult.OK Then rtb.SelectionFont = fd.Font End If End Sub

Private Sub btn_Color_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Color.Click If cd.ShowDialog = Windows.Forms.DialogResult.OK Then rtb.SelectionColor = cd.Color End If End Sub

58 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btn_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Save.Click If sd.ShowDialog = Windows.Forms.DialogResult.OK Then rtb.SaveFile(sd.FileName) End If End Sub Private Sub btn_open_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_open.Click If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then rtb.LoadFile(ofd.FileName) End If End Sub Private Sub btn_New_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_New.Click rtb.Clear() End Sub Private Sub btn_Close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Close.Click Me.Close() End Sub End Class Note: 1. Above Control is Rich Texbox and it name property set as rtb 2. Take FontDialogbox, ColorDialogBox, SaveDialogBox, and OpenDialogbox Controls From ToolBox Which is Under the Dialog Tab.

59 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO.NET
ADO.Net Architecture

Connected Model Application

Disconnected Model Application Data Set Data Reader

Command

Data Reader Data Adapter

Connection

Connection

INTRODUCTION:

ADO.Net Is Essentially A Collection Of Classes That Expose Methods And Attributes


60 VB.Net

D a t a b a s e

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Used To Manage Communication Between An Application And A Database. An Integral Part Of The .Net Framework, ADO.Net Simplifies Database Programming In Visual Studio .NET. THE STANDARD ADO OBJECTS ARE: Connection A Connection, As The Name Implies Wraps The Concept Of A Connection With The Database. We Must Have A Connection Before We Can Execute A Command And Read Data From A Database. Command A Command Represent An Instruction Being Send To The Database In Form Of SQL Statements Such As Select, Insert, Update, Delete Or A Name Of A Stored Procedure. DataReader The Datareader is like a forwardonly, Readonly Cursor to the records retrieved by the Commands Select Statement, in the front end.

Imports System.Data.SqlClient

Public Class Frm_DML


Dim con As SqlConnection Dim cmd As SqlCommand Dim dr As SqlDataReader

Private Sub btninsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btninsert.Click


cmd = New SqlCommand cmd.CommandType = CommandType.Text cmd.CommandText = Insert into emp values(@empno, @ename, @job, @sal)

Private Sub Frm_DML_Load(ByVal sender As Object, ByVal e As


61

VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

System.EventArgs) Handles Me.Load


con = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=sfk_db;Integrated Security=True")

End Sub Public Sub clear()


txtempno.Clear() txtname.Clear() txtjob.Clear() txtsal.Clear() txtempno.Focus()

cmd.Parameters.AddWithValue ("@empno", txtempno.Text.Trim()) cmd.Parameters.AddWithValue ("@ename", txtname.Text.Trim()) cmd.Parameters.AddWithValue ("@job", txtjob.Text.Trim()) cmd.Parameters.AddWithValue ("@sal", txtsal.Text.Trim()) cmd.Connection = con Try cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) End Try clear()

End Sub

End Sub

Private Sub btnselect_Click(ByVal sender Else MsgBox("No such Empno Exist") As Object, ByVal e As End If System.EventArgs) Handles btnselect.Click dr.Close()
If txtempno.Text.Trim.Length = 0 Then MsgBox("Enter a Empno") Else cmd = New SqlCommand cmd.CommandType = CommandType.Text cmd.CommandText = "Select * from emp where empno = " + txtempno.Text If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con Try Catch ex As Exception MsgBox(ex.Message) End Try con.Close() End If

End Sub

Private Sub btndelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btndelete.Click


cmd = New SqlCommand cmd.CommandType = CommandType.Text cmd.CommandText =

62 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 dr = cmd.ExecuteReader If dr.HasRows = True Then cmd.Connection = con While (dr.Read) Try txtempno.Text = dr(0) txtname.Text = dr(1) txtjob.Text = dr(2) txtsal.Text = dr("sal") End While cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) End Try clear() "Delete from emp where empno=" + txtempno.Text

End Sub

63 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btnupdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnupdate.Click


cmd = New SqlCommand cmd.CommandType = CommandType.Text cmd.CommandText = "update emp set ename=@ename, job=@job, sal=@sal where empno=@empno cmd.Parameters.AddWithValue ("@empno", txtempno.Text.Trim()) cmd.Parameters.AddWithValue ("@ename", txtname.Text.Trim()) cmd.Parameters.AddWithValue ("@job", txtjob.Text.Trim()) cmd.Parameters.AddWithValue ("@sal", txtsal.Text.Trim()) cmd.Connection = con Try cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) End Try clear()

End Sub

64 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO USING STORED PROCEDURE

Imports System.Data.SqlClient

Public Class Form1


Dim con As SqlConnection Dim cmd As SqlCommand Dim dr As SqlDataReader Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load con = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=sfk_db;Integrated Security=True;Pooling=False")

Private Sub btninsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninsert.Click


cmd = New SqlCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "InsEmp" cmd.Parameters.AddWithValue ("@empno", txtempno.Text.Trim()) cmd.Parameters.AddWithValue ("@ename", txtname.Text.Trim()) cmd.Parameters.AddWithValue ("@job", txtjob.Text.Trim()) cmd.Parameters.AddWithValue ("@sal", txtsal.Text.Trim()) If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con Try cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) End Try clear()

End Sub Public Sub clear()


txtempno.Clear() txtname.Clear() txtjob.Clear() txtsal.Clear() txtempno.Focus()

End Sub

65 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Sub Private Sub btnselect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnselect.Click
If txtempno.Text.Trim.Length = 0 Then MsgBox("Enter a Empno") Else cmd = New SqlCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "GetEmp" If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con cmd.Parameters.AddWithValue ("@empno", txtempno.Text.Trim()) Try dr = cmd.ExecuteReader If dr.HasRows = True Then While (dr.Read) txtempno.Text = dr(0) txtname.Text = dr(1) txtjob.Text = dr(2) txtsal.Text = dr("sal") End While Else MsgBox("No such Empno Exist", MsgBoxStyle.Exclamation, "SFK") End If dr.Close() Catch ex As Exception MsgBox(ex.Message) End Try con.Close()

Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click


cmd = New SqlCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "DelEmp" If con.State = ConnectionState.Closed Then con.Open() End If cmd.Parameters.AddWithValue ("@empno", txtempno.Text) cmd.Connection = con Try cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) End Try clear()

End Sub Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
cmd = New SqlCommand cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "UpdEmp" If con.State = ConnectionState.Closed Then con.Open() End If

66 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 End If

End Sub
cmd.Parameters.AddWithValue ("@empno", txtempno.Text.Trim()) cmd.Parameters.AddWithValue ("@ename", txtname.Text.Trim()) cmd.Parameters.AddWithValue ("@job", txtjob.Text.Trim()) cmd.Parameters.AddWithValue ("@sal", txtsal.Text.Trim()) cmd.Connection = con Try cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message) End Try clear() CREATE PROCEDURE UpdEmp @empno int, @eName varchar(20), @job varchar(10), @sal int AS update emp set ename=@ename, job=@job, sal=@sal where empno=@empno

CREATE PROCEDURE InsEmp @empno int, @eName varchar(20), @job varchar(10), @sal int AS insert into emp(empno,ename,job,sal) values(@empno,@ename,@job,@sal)

End Sub End Class /* Stored Procedures */


CREATE PROCEDURE GetEmp @empno int AS select * from emp where empno=@empno

CREATE PROCEDURE DelEmp @empno int AS delete from emp where empno=@empno

67 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

68 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO.NET DISCONNECTED MODEL


DataSet: The Dataset is the Central Component in ADO.Net Disconnected Data Access Architecture. The ADO.Net Architecture uses Dataset Object for in-memory representation of data i.e.: A Local Copy of the Data from in Database in the Application (Front End). Once the Dataset is Populated, Accessing the data in the Dataset does not require interaction with the database, and changes to data in the dataset have no effect on the database, until the changes are updated with the Database. Hence, this is called as ADO.Net Disconnected Model. A DataSet is Like a Collection of Tables in Front End, as it may contain multiple Tables, each of which will have a collection of Columns and Rows. A DataSet May Also Contain Integrity Constraints and Relationships. DataAdapter: A DataAdapter is responsible for moving the Data between the Datasource (Database) and the DataSet (Application / Front End). The DataAdapter incorporates the functionality required to Retrieve Data, Populate DataSet & Perform Updates of the Database. Some of the Important Properties of a DataAdapter are SELECTCOMMAND, CONNECT & Important Methods are FILL, UPDATE. You Can Populate the DataSet by calling the DataAdapter.Fill() Method, which will execute the instructions contained in the DataAdapter.SelectCommand Property over the connections specified by the DataAdapter.Connection Property. If The Changes Made to the Data in DataSet is to be reflected in the Database, then the DataAdapter.Update Method may be called. To Update the Database with the changes made to the DataSet, the DataAdapter by itself cannot generate the SQL statements required for the Database. To Automatically Generate the SQL statements, we may use SQLCOMMANDBUILDER.

69 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Imports System.Data.SqlClient

Public Class Form1


Dim Dim Dim Dim Dim con As SqlConnection da As SqlDataAdapter ds As DataSet cmdBldr As SqlCommandBuilder Dtrow As DataRow

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


con = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=sfk_db;Integrated Security=True;Pooling=False") 'con.Open() da = New SqlDataAdapter("Select * From Emp", con) ds = New DataSet() da.Fill(ds) dg.DataSource = ds.Tables(0) 'da.Fill(ds, "emp") 'dg.DataSource = ds.Tables("emp")

70 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Sub Private Sub btninsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninsert.Click
'adding a new row to the table(0) in dataset DS. Dtrow = ds.Tables(0).NewRow() Dtrow(0) Dtrow(1) Dtrow(2) Dtrow(3) = = = = txtempno.Text txtname.Text txtjob.Text txtsal.Text

adding values to the newly added row of the table in dataset. ds.Tables(0).Rows.Add(Dtrow) clear()

End Sub Public Sub clear()


txtempno.Clear() txtname.Clear() txtjob.Clear() txtsal.Clear() txtempno.Focus()

End Sub Private Sub btnselect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnselect.Click
Declaring an Array of Datarow to hold all the Rows of the Table. Dim dtr() As DataRow dtr = ds.Tables(0).Select("empno=" + txtempno.Text)

'Fetching one the rows into the textboxs from the dataset If (dtr.Length = 0) Then MsgBox("Item Not Found") Else Dtrow = dtr(0)

71 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 txtname.Text = Dtrow(1) txtjob.Text = Dtrow(2) txtsal.Text = Dtrow(3) End If

End Sub Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
Updating the DataSet with changes made in the textboxes Dtrow(0) = txtempno.Text Dtrow(1) = txtname.Text Dtrow(2) = txtjob.Text Dtrow(3) = txtsal.Text clear()

End Sub Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
Delete the row from the dataset Dtrow.Delete() clear()

End Sub Private Sub Btn_Send_To_DB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Send_To_DB.Click
Sending the Insert, Update, Delete Changes made to the DataSet to the Database Try cmdBldr = New SqlCommandBuilder(da) da.Update(ds) Catch ex As Exception MsgBox(ex.Message) End Try

End Sub End Class

72 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Data Binding : Imports System.Data.SqlClient


Public Public Public Public Public Class emp_database con As SqlConnection da As SqlDataAdapter dt As DataTable ds As DataSet

Public Sub New() con = New SqlConnection("Data Source=.\sqlexpress;AttachDbFilename=D:\Ainna\Project\deccan\deccan \data\stud_addm.mdf;Integrated Security=True") con.Open() da = New SqlDataAdapter("select * from emp", con) ds = New DataSet() da.Fill(ds) dt = ds.Tables(0) End Sub

End Class

Import system.io Import system.data.sqlclient Clss Frm_emp Dim con as sqlconnection Dim cmd as sqlcommond Dim dr as sqldatareader Dim emp_db as new emp_database

73 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Private Sub Frm_stud_photo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load con = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=stud_addm;Integrated Security=True") con.Open() Try txtempno.DataBindings.Add("text", emp_db.dt, "empno") txtename.DataBindings.Add("text", emp_db.dt, "ename") txtjob.DataBindings.Add("text,emp_db.dt, "job") Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub btn_decrement_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_decrement.Click Me.BindingContext(emp_db.dt).Position -= 1 End Sub Private Sub btn_increment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_increment.Click Me.BindingContext(emp_db.dt).Position += 1 End Sub Private Sub btn_low_record_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_low_record.Click Me.BindingContext(emp_db.dt).Position = 0 End Sub Private Sub btn_high_record_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_high_record.Click Me.BindingContext(emp_db.dt).Position = Me.BindingContext(emp_db.dt).Count - 1 End Sub

74 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

ADO_DS_ORCL

Imports System.Data.OracleClient

Public Class ADO_DS_ORCL


Dim Dim Dim Dim Dim Dim ds As DataSet daemp As OracleDataAdapter dadept As OracleDataAdapter cmdbld As OracleCommandBuilder con As OracleConnection dtr As DataRow

75 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub ADO_DS_ORCL_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


con = New OracleConnection("User=scott; password=tiger) daemp = New OracleDataAdapter("Select empno,ename,job,sal,deptno from emp", con) ds = New DataSet daemp.Fill(ds, "emp") dg.DataSource = ds.Tables(0) Populating the ComboBox for Empno Dim i As Integer For i = 0 To ds.Tables(0).Rows.Count - 1 cboEmpno.Items.Add(ds.Tables(0).Rows(i)(0)) Next Declaring a Data Set for Populating ComboBox for Deptno dadept = New OracleDataAdapter("Select deptno from dept", con) dadept.Fill(ds, "dept") For i = 0 To ds.Tables(1).Rows.Count - 1 cbodpt.Items.Add(ds.Tables(1).Rows(i)(0)) Next

End Sub Private Sub cboEmpno_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboEmpno.SelectedIndexChanged Dim dtrow() As DataRow
dtrow = ds.Tables(0).Select("empno=" + cboEmpno.Text) dtr = dtrow(0) txtname.Text = dtr(1) txtjob.Text = dtr(2) txtsal.Text = dtr(3) cbodpt.SelectedItem = dtr(4)

End Sub

76 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Private Sub btnselect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnselect.Click


Dim dtrow() As DataRow dtrow = ds.Tables(0).Select("empno=" + cboEmpno.Text) If dtrow.Length = 0 Then MsgBox("Empno Does Not Exist") Else dtr = dtrow(0) txtname.Text = dtr(1) txtjob.Text = dtr(2) txtsal.Text = dtr(3) cbodpt.SelectedItem = dtr(4) End If

End Sub Private Sub dg_CellEnter(ByVal sender As System.Object, ByVal


e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dg.CellEnter Dim dtrow() As DataRow dtrow = ds.Tables(0).Select("empno=" + dg(0,e.RowIndex).Value.ToString) dtr = dtrow(0) cboEmpno.Text = dtr(0) txtname.Text = dtr(1) txtjob.Text = dtr(2) txtsal.Text = dtr(3) cbodpt.SelectedItem = dtr(4)

End Sub Private Sub btninsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninsert.Click
dtr = ds.Tables(0).NewRow() dtr(0) dtr(1) dtr(2) dtr(3) dtr(4) = = = = = cboEmpno.Text txtname.Text txtjob.Text txtsal.Text cbodpt.Text

ds.Tables(0).Rows.Add(dtr)

77 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

End Sub Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
dtr(0) dtr(1) dtr(2) dtr(3) dtr(4) = = = = = cboEmpno.Text txtname.Text txtjob.Text txtsal.Text cbodpt.Text

End Sub Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
dtr.Delete()

End Sub Private Sub Btn_Send_To_DB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Send_To_DB.Click
cmdbld = New OracleCommandBuilder(daemp) daemp.Update(ds.Tables(0))

End Sub End Class

78 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Image Storing In Database

Imports System.Data.SqlClient Imports System.IO Public Class Frm_Image_Demo Dim con As SqlConnection Dim cmd As SqlCommand Dim photo() As Byte Dim dr As SqlDataReader Private Sub Frm_Image_Demo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load con = New SqlConnection("Data Source=.;Initial Catalog= Test;Integrated Security=True") con.Open() End Sub Private Sub btn_Imageload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Imageload.Click If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then pbphoto.Load(OFD.FileName) End If End Sub Private Sub btn_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click 79 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Try cmd = New SqlCommand cmd.CommandText = "Insert into sphoto values(@sid,@name,@photo)" cmd.Parameters.AddWithValue("@sid", txtsid.Text) cmd.Parameters.AddWithValue("@name", txtsname.Text) photo = File.ReadAllBytes(pbphoto.ImageLocation) photo = File.ReadAllBytes(OFD.FileName) cmd.Parameters.AddWithValue("@photo", photo) If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con cmd.ExecuteNonQuery() MsgBox("Image Saved...!") Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub btn_Select_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Select.Click Try cmd = New SqlCommand cmd.CommandText = "Select Name,Photo From Sphoto Where sid=@sid" cmd.Parameters.AddWithValue("@sid", txtsid.Text) If con.State = ConnectionState.Closed Then con.Open() End If cmd.Connection = con dr = cmd.ExecuteReader If dr.Read() Then txtsname.Text = dr(0) photo = dr(1) File.WriteAllBytes("Photo.jpg", photo) pbphoto.Load("Photo.jpg") Else MsgBox("No Such Record Exist") End If Catch ex As Exception MsgBox(ex.Message) Finally con.Close() dr.Close() 80 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 End Try End Sub Private Sub btn_close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_close.Click Me.Close() End Sub Private Sub btn_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_clear.Click txtsid.Clear() txtsname.Clear() pbphoto.Image = Nothing End Sub End Class Note: 1. Set the SizeMode Property of Picture Box To Strech Image. 3. For Saving Image In SQL Server Database Take Data Type as Image or Varbinary

Crystal Reports
Crystal Report is a business intelligence application used to design and generate report from a wide range of data sources. Several other application, such as Microsoft Visual Studio, bundle an OEM version of Crystal Report as a general purpose reporting tool, Crystal Reports became the de facto standard report writer when Microsoft Released it with Visual Studio.

The product was originally created by Crystal Services Inc. as Quick Reports when they couldnt find a suitable commercial report writer for their accounting software. After producing version 1.0 through 3.0, the company was acquired in 1994 by Seagate Technology. Crystal Services was combined with Holostic Systems to form the Information Management Group of Seagate Software, which later rebranded as Crystal Decision, and produced version 4.0 through 9.0. Crsytal Decision was acquired in December 2003 by Business Objects, which has so far produced version 10, 11(XI) and the current verison 12.

81 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Business Objects was acquired by SAP on OCT 8, 2007. If we want to add a report under a .Net project open Add New Item window & select Reporting in LHS panel, then select Crystal Report from RHS panel, which adds a Report file, with an extension .rpt. A report when opened has 5 section in it: 1. Report Header 2. Page Header 4. Report Footer 5. Page Footer 3. Details

Report Header: Content placed under this section gets displayed at top of the report i..e on top of the first page in report e.g.: Company Name, Address etc. Page Header: Content placed under this section gets displayed at top of every page in to which the report extends. e.g.: Column Names, Date, Time etc. Details: Contents into this section generally comes from the DB; this is the actual information that has to be presented to clients. Report Footer: this is same as Report Header but gets displayed at bottom of report e.g.: Signatures, Date & Place. Page Footer: this is same as Page Header but gets displayed at bottom of every page into which the report extends. e.g.: Page Nos Creating a Report: open a new project of type Windows, name it ReportProject, open add new item window, select Reporting on LHS, choose Crystal Report on RHS, name the report as Sample.rpt, choose blank report option, click OK. As the report has to get its information from DB first we need to configure the report with appropriate data source using the Field Explorer window that getds added along with Report (Shorcut:Ctrl+Alt+T).

Configuring the Report with DB: Open the field explorer, right click on DB Field Node, select Database Expert list of providers, choose Microsoft OLEDB Provider for Sql Server, click next, specify the connection details like server name, user id, password & DB, click Finish which adds a node under OLEDB(ADO), expand the nodes below: CSharp, dbo, Tables, double click on the table we want to consume, e.g.: Customer, adds table under selected tables list, click ok, adds selected table under DB fields node of Field Explorer.

82 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Designing the Report: go into Report Header Section right click in it and select Insert Text Object that adds an object like a Label, enter content in it & do required alignment using the format toolbar on top.

Goto Page Header section right click on it & Select Insert -> Special Field -> DataDate, place it on LHS of the section, right click on it select format object and choose the format in which we want to display the date, in the same way select DataTime & place it on RHS.

Now open Field Explorer and expand the table Customer we have selected, that displays the list of columns below, drag and drop each column on to details section as per your design which will create 1 field on the Page Header (Column Name) and 1 Field on the Details(Data).

Now go to Report Footer & Provider the option for users to enter Date, Place and Signature using the Text Objects and Insert Line Options.

Now go the Page Footer section right click Insert -> Special Field -> select Page Number and place it on the Center of the section.

Launching the Report: to display a report we need to use the control CrystalReportViewer that has to be placed on Form which will be default use Dock property as Fill. If we want to show a report under the control first it has to be loaded into the app from its physical location.

Place a CrystalReportViewer control on form and write the following code: Under Form Load: crystalReportViewer1.ReportSource=<path of report>; Note: To get path of your report goto Solution Explorer, right click on crystal report file & select properties, copy value under FullPath property and use it.

83 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

84 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372 Imports CrystalDecisions.CrystalReports.Engine Public Class Frm_Report_Demo Dim rptpath As String Dim rptdoc As ReportDocument

Private Sub Frm_Report_Demo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load rptdoc = New ReportDocument rptpath = "D:\Akbar\Report_Demo\Report_Demo\Rpt_EmpDetail.rpt" rptdoc.Load(rptpath) CV1.ReportSource = rptdoc End Sub Private Sub btn_close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_close.Click Me.Close() End Sub End Class

85 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared


Public Class cry_rpt Dim rptpath As String Dim rptdoc As ReportDocument

Private Sub btn_show_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_show.Click


rptdoc = New ReportDocument rptpath = "D:\crystal_demo\crystal_demo\addm_report.rpt" rptdoc.Load(rptpath) CV.ReportSource = rptdoc Dim Dim Dim Dim PFDs As ParameterFieldDefinitions PFD As ParameterFieldDefinition PValues As New ParameterValues PDis_Value As New ParameterDiscreteValue

PFDs_Value.Value = TextBox1.Text PFDs = rptdoc.DataDefinition.ParameterFields() PFD = PFDs.Item("class") PValues = PFD.CurrentValues PValues.Clear() PValues.Add(PDis_Value) PFD.ApplyCurrentValues(PValues) CV.ReportSource = rptdoc CV.Refresh() End Sub End Class 86 VB.Net

www.sfkinfotech.com Sarfaraz Khan - 9763987372

87 VB.Net

You might also like