Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 369

VB.

NET LANGUAGE BASICS TUTORIALS

VB.NET Language Basics


The following sections deals with vb.net data types , vb.net conversions and vb.net access specifiers etc.

VB.NET Data Types


DATATYPE in a programming language describes that what type of data a variable can hold . When we declare a variable, we have to tell the compiler about what type of the data the variable can hold or which data type the variable belongs to. Syntax : Dim VariableName as DataType VariableName : the variable we declare for hold the values. DataType : The type of data that the variable can hold VB.NET sample : Dim count As Integer count : is the variable name Integer : is the data type The above example shows , declare a variable 'count' for holding integer values. In the variable count we can hold the integer values in the range of -2,147,483,648 to +2,147,483,647. The follwing are the some of commonly using datatypes in vb.net.

Boolean Boolean variables are stored 16 bit numbers and it can hold only True or false. VB.NET Runtime type : System.Boolean VB.NET declaration : dim check as Boolean VB.NET Initialization : check = false VB.NET default initialization value : false Integer Integer variables are stored sighned 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647 VB.NET Runtime type : System.Int32 VB.NET declaration : dim count as Integer VB.NET Initialization : count = 100 VB.NET default initialization value : 0 String String variables are stored any number of alphabetic, numerical, and special characters . Its range from 0 to approximately 2 billion Unicode characters. VB.NET Runtime type : System.String VB.NET declaration : Dim str As String

VB.NET Initialization : str = "String Test" VB.NET default initialization value : Nothing In VisualBasic.Net we can convert a datatype in two ways. Implicit Conversion and Explicit conversion . Also we can convert a type value to a reference and reference value to a type value. These are called Boxing and unBoxing . Boxing referes value type to reference type and unboxing , reference type ot value type.
Download Source Code Print Source Code

Take our 3-Minute Hosting Decisions Survey Introducing HTML5 (Voices that Matter) Participants will be eligible to win a $100 Amazon gift certificate. Take Concentrating on the practical and the issues that HTML5 can solve the short survey here. "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim check As Boolean check = True MsgBox("The value assigned for check is : " & check) Dim count As Integer count = 100 MsgBox("The value holding count is Dim str As String str = "String test " MsgBox("The value holding str is End Sub End Class

: " & count)

: " & str)

When you execute this programme , you will get "true" in the first message box and , 100 in the second message box and "String Test" in the last message box.

VB.NET Implicit and Explicit Conversions

Implicit Type Conversions Implicit Conversion perform automatically in VB.NET, that is the compiler is taking care of the conversion. The following example you can see how it happen. 1. Dim iDbl As Double 2. Dim iInt As Integer 3. iDbl = 9.123 4. MsgBox("The value of iDbl is " iDbl) 5. iInt = iDbl 6. MsgBox("The value of iInt is " iInt) line no 1 : Declare a Double datatype variable iDble line no 2 : Declare an Integer datatyoe variable iInt line no 3 : Assign a decimal value to iDbl line no 4 : Display the value of iDbl line no 5 : Assign the value of iDbl to iInt line no 6 : Display the value of iInt The first messagebox display the value of iDbl is 9.123 The second messegebox display the value od iInt is 9

iInt display only 9 because the value is narrowed to 9 to fit in an Integer variable. Here the Compiler made the conversion for us. These type fo conversions are called Implicit Conversion . The Implicit Conversion perform only when the Option Strict switch is OFF
Download Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details. Print Source Code Lake Quincy Media Millions of developers: one call. The world's leading developer advertising group.

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim iDbl As Double Dim iInt As Integer iDbl = 9.123 MsgBox("The value of iDbl is " & iDbl) iInt = iDbl 'after conversion MsgBox("The value of iInt is " & iInt) End Sub End Class

Explicit Type Conversions In some cases we have to perform conversions , that is the compiler does not automatically convert a type to another . These type of conversion is called Explicit conversion . An explicit conversion uses a type conversion keyword. With these conversion keywords we hav to perform the Explicit Conversion.

How to VB.NET Access Specifiers

AccessSpecifiers describes as the scope of accessibility of an Object and its members. We can control the scope of the member object of a class using access specifiers. We are using access specifiers for providing security of our applications. Visual Basic .Net provide five access specifiers , they are as follows : Public, Private , Protected , Friend and ProtectedFriend . Public : Public is the most common access specifier. It can be access from anywhere, hat means there is no restriction on accessability. The scope of the accessibility is inside class also in outside the class. Private : The scope of the accessibility is limited only inside the classes in which they are decleared. The Private members can not be accessed outside the class and it is the least permissive access level. Protected : The scope of accessibility is limited within the class and the classses derived (Inherited )from this class. Friend : The Friend access specifier can access within the program that contain its declarations and also access within the same assembly level. You can use friend instead of Dim keyword. ProtectedFriend : ProtectedFriend is same access lebels of both Protected and Friend. It can access anywhere in the same assebly and in the same class also the classes inherited from the same class .

How to VB.NET Exceptions

Exceptions are the occurrence of some condition that changes the normal flow of execution . For ex: you programme run out of memory , file does not exist in the given path , network connections are dropped etc. More specifically for better understanding , we can say it as Runtime Errors . In .NET languages , Structured Exceptions handling is a fundamental part of Common Language Runtime . It has a number of advantages over the On Error statements provided in previous versions of Visual Basic . All exceptions in the Common Language Runtime are derived from a single base class , also you can create your own custom Exception classes. You can create an Exception class that inherits from Exception class . You can handle Exceptions using Try..Catch statement .
Try code exit from Try Catch [Exception [As Type]] code - if the exception occurred this code will execute exit from Catch

Finally The code in the finally block will execute even if there is no Exceptions. That means if you write a finally block , the code should execute after the execution of try block or catch block.
Try code exit from Try Catch [Exception [As Type]] code - if the exception occurred this code will execute exit Catch Finally code - this code should execute , if exception occurred or not

From the following VB.NET code , you can understand how to use try..catch statements. Here we are going to divide a number by zero .

Download Source Code

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim i As Integer Dim resultValue As Integer i = 100 resultValue = i / 0 MsgBox("The result is " & resultValue) Catch ex As Exception MsgBox("Exception catch here ..") Finally MsgBox("Finally block executed ") End Try End Sub End Class

When you execute this program you will "Exception catch here .." first and then "Finally block executed " . That is when you execute this code , an exception happen and it will go to catch block and then it will go to finally block.

VB.NET Option Explicit [On | Off]


Option Explicit statement ensures whether the compiler requires all variables to be explicitly declared or not before it use in the program. Option Explicit [On Off] The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON , you have to declare all the variable before you use it in the program . If not , it will generate a compile-time error whenever a variable that has not been declared is encountered .If the Option Explicit mode is OFF , Vb.Net automatically create a variable whenever it sees a variable without proper declaration. By default the Option Explicit is On With the Option Explicit On , you can reduce the possible errors that result from misspelled variable names. Because in Option Explicit On mode you have to declare each variable in the program for storing data.

Take a look at the following programs, it will give you a clear picture of Option Explicit. The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The default is Option Explicit On , so we do not need to put it in the source code. VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim someVariable As String someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class

The above program , declare a String variable and assigned a value in it and it displays. Take a look at the following program , it is an example of Option Explicit Of Download Source Code Print Source Code

Option Explicit Off Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class

Here "someVariable" is not declared , because the Option Explicit Of , without any compiler error you can continue the program

VB.NET Option Strict [On | Off]


Option Strict is prevents program from automatic variable conversions, that is implicit data type conversions .

Option Strict [On Off] By default Option Strict is Off From the following example you can understand the use of Option Strict. VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum MsgBox(intNum) End Sub End Class

The above program is a normal vb.net program and is in default Option Strict Off . Because its Option Strict Off we can convert the value of Long to an Integer. Take a look at the following program. Download Source Code Print Source Code

Option Strict On Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum

MsgBox(intNum) End Sub End Class

When you write this source code the compiler will shows the message "Option Strict On disallows implicit conversions from 'Long' to 'Integer'" The compiler generate error because in the program we put "Option Strict On" and prevent the program from automatic conversion.

VB.NET On Error GoTo


On Error GoTo statements is an example of Vb.Net's Unstructured Exception Handling . VB.NET has two types of Exception handling . Structured Error Handling and Unstructured Error handling . VB.NET using Try..Catch statement for Structured Error handling and On Error GoTo statement is using for Unstructured Error handling. Error GoTo redirect the flow of the program in a given location. On Error Resume Next - whenever an error occurred in runtime , skip the statement and continue execution on following statements. Take a look at the following program VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim result As Integer Dim num As Integer num = 100 result = num / 0 MsgBox("here") End Sub End Class

when u execute this program you will get error message like " Arithmetic operation resulted in an overflow " See the program we put an On Error GoTo statement Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo nextstep Dim result As Integer Dim num As Integer num = 100 result = num / 0 nextstep: MsgBox("Control Here") End Sub End Class

When you execute the program you will get the message box "Control Here" . Because the On Error statement redirect the exception to the Label statement.

Operating System Information


The following VB.NET program retrieves the current operating system information like version and platform identifier with the help of OperatingSystem Class and Environment Class. The OperatingSystem Class provides a method to copy an instance of OperatingSystem, and a method to return a string representation of operating system information. The OperatingSystem class is not a general purpose class and you cannot derive a more inclusive type from the OperatingSystem class. If you need a type to contain other information about an operating system, create your own type, then include a field of type OperatingSystem and any additional fields, properties, or methods you require.

The Environment Class provides information about, and means to manipulate, the current environment and platform. The Environment Class has a property called OSVersion which returns an object of type OperatingSystem.
Dim _os As OperatingSystem _os = Environment.OSVersion

Download Source Code


Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim _os As OperatingSystem _os = Environment.OSVersion MsgBox(_os.VersionString.ToString) End Sub End Class

Operating System Information


The following VB.NET program retrieves the current operating system information like version and platform identifier with the help of OperatingSystem Class and Environment Class. The OperatingSystem Class provides a method to copy an instance of OperatingSystem, and a method to return a string representation of operating system information. The OperatingSystem class is not a general purpose class and you cannot derive a more inclusive type from the OperatingSystem class. If you need a type to contain other information about an operating system, create your own type, then include a field of type OperatingSystem and any additional fields, properties, or methods you require.

The Environment Class provides information about, and means to manipulate, the current environment and platform. The Environment Class has a property called OSVersion which returns an object of type OperatingSystem.
Dim _os As OperatingSystem _os = Environment.OSVersion

Download Source Code


Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim _os As OperatingSystem _os = Environment.OSVersion MsgBox(_os.VersionString.ToString) End Sub End Class

VB.NET PROGRAM FLOW CONTROLS TUTORIALS

VB.NET Program Flow Control Tutorials


In the following sections you can see in detail how to use the Conditional Statement like IF ELSE and the Loops like For..NEXT , While..END WHILE etc.

How to use IF ELSE in VB.NET


The conditional statement IF ELSE , is use for examining the conditions that we provided, and making decision based on that contition. The conditional statement examining the data using comparison operators as well as logical operators.

If [your condition here] Your code here Else Your code Here End If

If the contition is TRUE then the control goes to between IF and Else block , that is the program will execute the code between IF and ELSE statements. If the contition is FLASE then the control goes to between ELSE and END IF block , that is the program will execute the code between ELSE and END IF statements. If you want o check more than one condition at the same time , you can use ElseIf .
If [your condition here] Your code here ElseIf [your condition here] Your code here ElseIf [your condition here] Your code here Else Your code Here End If

Just take a real-time example - When we want to analyze a mark lists we have to apply some conditions for grading students depends on the marks. Following are the garding rule of the mark list: 1) If the marks is greater than 80 then the student get higher first class 2) If the marks less than 80 and greater than 60 then the student get first class 3) If the marks less than 60 and greater than 40 then the student get second class

4) The last condition is , if the marks less than 40 then the student fail. Now here implementing these conditions in a VB.NET program.
1. 2. 3. 4. 5. 6. 7. 8. 9. If totalMarks >= 80 Then MsgBox("Got Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Got First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If

Line 1 : Checking the total marks greaterthan or equal to 80 Line 2 : If total marks greater than 80 show message - "Got Higher First Class " Line 3 : Checking the total marks greaterthan or equal to 60 Line 4 : If total marks greater than 60 show message - "Got First Class " Line 5 : Checking the total marks greaterthan or equal to 40 Line 6 : If total marks greater than 40 show message - "Just pass only" Line 7 : If those three conditions failed program go to the next coding block Line 8 : If all fail shows message "Failed" Line 9 : Ending the condition block VB.NET Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim totalMarks As Integer totalMarks = 59 If totalMarks >= 80 Then MsgBox("Gor Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Gor First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If End Sub End Class

In this example the total marks is 59 , when you execute this program you will get in messagebox "Just Pass Only" If you want to check a condition within condition you can use nested if statements
If [your condition here] If [your condition here] Your code here Else Your code Here End If Else Your code Here End If

Also you can write IF ELSE Statements in a single line If [your condition here] [Code] Else [code] Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim totalMarks As Integer totalMarks = 39 If totalMarks >= 50 Then MsgBox("passed ") Else MsgBox("Failed ") End Sub End Class

When you execute this program you will get in messagebox "Failed "

How to use FOR NEXT loop in vb.net


Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you have to repeat a task till you reach a condtition, in these situations you can use loop statements to achieve your desired results. FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.NET 2005 ( VB.NET 2005) . FOR NEXT Loop : The FOR NEXT Loop , execute the loop body (the source code within For ..Next code block) to a fixed number of times.
For var=[startValue] To [endValue] [Step] [loopBody] Next [var]

var : The counter for the loop to repeat the steps. starValue : The starting value assign to counter variable . endValue : When the counter variable reach end value the Loop will stop .

loopBody : The source code between loop body Lets take a simple real time example , If you want to show a messagebox 5 times and each time you want to see how many times the message box shows.
1. 2. 3. 4. 5. startVal=1 endVal = 5 For var = startVal To endVal show message Next var

Line 1: Loop starts value from 1 Line 2: Loop will end when it reach 5 Line 3: Assign the starting value to var and inform to stop when the var reach endVal Line 4: Execute the loop body Line 5: Taking next step , if the counter not reach the endVal VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " & var & " Times ") Next var End Sub

End Class

When you execute this program , It will show messagebox five time and each time it shows the counter value. If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop body.
For var=startValue To endValue [Step] [loopBody] Contition [Exit For] Next [var]

Download Source Code

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " var " Times ") If var = 3 Then Exit For End If Next var End Sub End Class

When you execute the above source code , the program shows the message box only three times .

How to use FOR EACH loop in VB.NET

Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you have to repeat a task till you reach a condition, in these situations you can use loop statements to achieve your desired results. FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.NET 2005 ( VB.NET 2005) . For Each Loop FOR EACH Loop usually using when you are in a situation to execute every single element or item in a group (like every single element in an Array, or every single files in a folder or , every character in a String ) , in these type of situation you can use For Each loop.
For Each [Item] In [Group] [loopBody] Next [Item]

Item : The Item in the group Group : The group containing items LoopBody : The code you want to execute within For Each Loop Let's take a real time example , if you want to display the each character in the website name "HTTP://NET-INFORMATIONS.COM" , it is convenient to use For Each Loop.
1. siteName = "HTTP://NET-INFORMATIONS.COM" 2. For Each singleChar In siteName 3. MsgBox(singleChar) 4. Next

Line 1: Assigning the site name in a variable

Line 2: This line is extracting the single item from the group Line 3: Loop body Line 4: Taking the next step Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim siteName As String Dim singleChar As Char siteName = "HTTP://NET-INFORMATIONS.COM" For Each singleChar In siteName MsgBox(singleChar) Next End Sub End Class

When you execute this program you will get each character of the string in Messagebox.

How to use vb.net While End While loop


Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you have to repeat a task till you reach a condition, in these situations you can use loop statements to achieve your desired results. FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.NET 2005 ( VB.NET 2005) . While ..End While While .. End While Loop execute the code body (the source code within While and End while statements ) until it meets the specified condition.

While [condition] [loop body] End While

Condition : The condition set by the user


1. counter = 1 2. While (counter <= 10) 3. Message 4. counter = counter + 1 5. End While

Line 1: Counter start from 1 Line 2: While loop checking the counter if it is less than or equal to 10 Line 3: Each time the Loop execute the message and show Line 4: Counter increment the value of 1 each time the loop execute Line 5: End of the While End While Loop body Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim counter As Integer counter = 1 While (counter <= 10) MsgBox("Counter Now is : " counter) counter = counter + 1 End While End Sub

End Class

When you execute the program 10 times the message shows with counter and exit from the While .. End While loop.

Custom Exceptions in VB.NET


Visual Basic .NET offers structured exception handling that provides a powerful, more readable alternative to "On Error Goto" error handling, which is available in previous versions of Microsoft Visual Basic. In VB.Net we can handle exceptions with great ease and we can also create our own customized exceptions which can later be used for our applications specific needs. Exceptions are objects that encapsulate an irregular circumstance, such as when an application is out of memory, a file that cannot be opened, or an attempted illegal cast. You can also throw an exception from within your own code using the keyword Throw.
Try your code block Catch ex As Exception exception handling block Finally final cleanup block End Try

The following VB.NET program shows, how to create a custom exception class and how it is using in the program. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim i As Integer

Print Source Code

Dim j As Integer Dim k As Integer j = 10 k = 0 i = j / k Catch ex As Exception Throw (New MyCustomException("You can not divide a number by zeo")) End Try End Sub End Class Public Class MyCustomException Inherits System.ApplicationException Public Sub New(ByVal message As String) MyBase.New(message) MsgBox(message) End Sub End Class

Multi dimensional String Array


An array allows to refer related values by the same name and to use a number, called an index or subscript, to tell them apart. The individual values are called the elements of the array.
Dim values() As Double

An array that uses more than one index or subscript is called multidimensional. A dimension is a direction in which you can vary the specification of an arrays elements. Some arrays have two dimensions, therefore, such an array uses two indexes. The following example declares a variable to hold a twodimensional array of office counts, for buildings 0 through 40 and floors 0 through 5.
Dim offices(40, 5) As Byte

The following VB.NET program shows a simple example of how to insert values in a two dimensional array and retrieve the values from two dimensional array. Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i, j As Integer Dim strArr(1, 2) As String strArr(0, 0) = "First (0,0)" strArr(0, 1) = "Second (0,1)" strArr(1, 0) = "Third (1,0)" strArr(1, 1) = "Fourth (1,1)" For i = 0 To strArr.GetUpperBound(0) For j = 0 To strArr.GetUpperBound(0) MsgBox(strArr(i, j)) Next Next End Sub End Class

VB.NET CONNECTIONS

VB.NET Collections
Visual Basic .NET Collections are data structures that holds data in different ways for flexible operations . The important datastructres in the Colletions are ArrayList , HashTable , Stack and Queue etc. In the following chapters you can see how to manage these datastructures in your visual basic.net (vb.net) programs.

How to VB.NET ArrayList

ArrayList is one of the most flixible data structure from VB.NET Collections. ArrayList contains a simple list of values and very easily we can add , insert , delete , view etc.. to do with ArrayList. It is very flexible becuse we can add without any size information , that is it grow dynamically and also shrink .
Important functions in ArrayList

Add : Add an Item in an ArrayList Insert : Insert an Item in a specified position in an ArrayList Remove : Remove an Item from ArrayList RemoveAt: remeove an item from a specified position Sort : Sort Items in an ArrayList How to add an Item in an ArrayList ? Syntax : ArrayList.add(Item) Item : The Item to be add the ArrayList Dim ItemList As New ArrayList() ItemList.Add("Item4") How to Insert an Item in an ArrayList ? Syntax : ArrayList.insert(index,item) index : The position of the item in an ArrayList Item : The Item to be add the ArrayList

ItemList.Insert(3, "item6") How to remove an item from arrayList ? Syntax : ArrayList.Remove(item) Item : The Item to be add the ArrayList ItemList.Remove("item2") How to remove an item in a specified position from an ArrayList ? Syntax : ArrayList.RemoveAt(index) index : the position of an item to remove from an ArrayList ItemList.RemoveAt(2) How to sort ArrayList ? Syntax : ArrayListSort() The following VB.NET source code shows some function in ArrayList
Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim ItemList As New ArrayList() ItemList.Add("Item4") ItemList.Add("Item5") ItemList.Add("Item2") ItemList.Add("Item1") ItemList.Add("Item3")

MsgBox("Shows Added Items") For i = 0 To ItemList.Count MsgBox(ItemList.Item(i)) Next 'insert an item ItemList.Insert(3, "Item6") 'sort itemms in an arraylist ItemList.Sort() 'remove an item ItemList.Remove("Item1") 'remove item from a specified ItemList.RemoveAt(3) MsgBox("Shows final Items the For i = 0 To ItemList.Count MsgBox(ItemList.Item(i)) Next End Sub End Class

index ArrayList") 1

When you execute this program , at first add five items in the arraylist and displays. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing items.

How to VB.Net HashTable


HashTable stores a Key Value pair type collection of data . We can retrive items from hashTable to provide the key . Both key and value are Objects. The common functions using in Hashtable are : Add : To add a pair of value in HashTable Syntax : HashTable.Add(Key,Value) Key : The Key value

Value : The value of corrosponding key ContainsKey : Check if a specified key exist or not Synatx : HashTable.ContainsKey(key) Key : The Key value for search in HahTable ContainsValue : Check the specified Value exist in HashTable Synatx : HashTable.ContainsValue(Value) Value : Search the specified Value in HashTable Remove : Remove the specified Key and corrosponding Value Syntax : HashTable.Remove(Key) Key : The argument key of deleting pairs The following source code shows all important operations in a HashTable Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim weeks As New Hashtable Dim day As DictionaryEntry weeks.Add("1", "Sun") weeks.Add("2", "Mon") weeks.Add("3", "Tue") weeks.Add("4", "Wed") weeks.Add("5", "Thu") weeks.Add("6", "Fri") weeks.Add("7", "Sat")

'Display a single Item MsgBox(weeks.Item("5")) 'Search an Item If weeks.ContainsValue("Tue") Then MsgBox("Find") Else MsgBox("Not find") End If 'remove an Item weeks.Remove("3") 'Display all key value pairs For Each day In weeks MsgBox(day.Key " -- " day.Value) Next End Sub End Class

When you execute this program it add seven weekdays in the hashtable and display the item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from HashTable. Finaly it displays all item exist in the HashTable.

How to VB.Net Stack


Stack is one of another easy to use VB.NET Collections . Stack follows the push-pop operations, that is we can Push Items into Stack and Pop it later also it follows the Last In First Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack returns the last item first.
Commonly used methods :

Push : Add (Push) an item in the stack datastructure Syntax : Stack.Push(Object) Object : The item to be inserted.

Pop : Pop return the item last Item to insert in stack Syntax : Stack.Pop() Return : The last object in the Stack Contains : Check the object contains in the stack Syntax : Stack.Contains(Object) Object : The specified Object to be seach The following VB.NET Source code shows some of commonly used functions :
Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stackTable As New Stack stackTable.Push("Sun") stackTable.Push("Mon") stackTable.Push("Tue") stackTable.Push("Wed") stackTable.Push("Thu") stackTable.Push("Fri") stackTable.Push("Sat") If stackTable.Contains("Wed") Then MsgBox(stackTable.Pop()) Else MsgBox("not exist") End If End Sub End Class

When you execute this program add seven items in the stack . Then its checks the item "Wed" exist in the Stack. If the item exist in the Stack , it Pop the last item from Stack , else it shows the msg "Not Exist"

How to VB.Net Queue


The Queue is another adtastructure from VB.NET Collections . Queue works like First In First Out method and the item added first in the Queue is first get out from Queue. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is get the reference of first item added in Queue ) the item from Queue.
The commonly using functions are follows :

Enqueue : Add an Item in Queue Syntax : Stack.Enqueue(Object) Object : The item to add in Queue Dequeue : Remove the oldest item from Queue (we dont get the item later) Syntax : Stack.Dequeue() Returns : Remove the oldest item and return. Peek : Get the reference of the oldest item (it is not removed permenantly) Syntax : Stack.Peek() returns : Get the reference of the oldest item in the Queue The following VB.NET Source code shows some of commonly used functions :

Download Source Code

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click Dim queueList As New Queue queueList.Enqueue("Sun") queueList.Enqueue("Mon") queueList.Enqueue("Tue") queueList.Enqueue("Wed") queueList.Enqueue("Thu") queueList.Enqueue("fri") queueList.Enqueue("Sat") MsgBox(queueList.Dequeue()) MsgBox(queueList.Peek()) If queueList.Contains("Sun") Then MsgBox("Contains Sun ") Else MsgBox("Not Contains Sun ") End If End Sub End Class

When you execute the program it add seven items in the Queue. Then it Dequeue (remove) the oldest item from queue. Next it Peek() the oldest item from Queue (shows only , not remove ). Next it check the Item "Sun" contains in the Queue.

How to VB.Net Arrays


Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index. Dim week(6) As String The above Vb.Net statements means that , an Array named as week declared as a String type and it can have the capability of seven String type values. week(0) = "Sunday"

week(1) = "Monday" In the above statement , we initialize the values to the String Array. week(0) = "Sunday" means , we initialize the first value of Array as "Sunday" , Dim weekName as String = week(1) We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array. In the following program , we declare an Array "week" capability of seven String values and assigns the seven values as days in a week . Next step is to retrieve the elements of the Array using a For loop. For finding the end of an Array we used the Length function of Array Object. Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim week(6) As String week(0) = "Sunday" week(1) = "Monday" week(2) = "Tuesday" week(3) = "Wednesday" week(4) = "Thursday" week(5) = "Friday" week(6) = "Saturday" For i = 0 To week.Length - 1 MsgBox(week(i)) Next End Sub End Class

When you execute this program you will get the Days in a Week .

How to VB.Net Dyanamic Array


Dynamic Arrays can resize the capability of the Array at runtime .when you are in a situation that you do not know exactly the number of elements to store in array while you making the program. In that situations we are using Dynamic Array . Initial declaration Dim scores() As Integer Resizing ReDim scores(1) If you want to keep the existing items in the Array , you can use the keyword Preserve . ReDim Preserve scores(2) In this case the Array dynamically allocate one more String value and keep the existing values. Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim scores() As Integer ReDim scores(1) scores(0) = 100 scores(1) = 200 For i = 0 To scores.Length - 1 MsgBox(scores(i)) Next

ReDim Preserve scores(2) scores(2) = 300 For i = 0 To scores.Length - 1 MsgBox(scores(i)) Next End Sub End Class

When you execute this source code , the first loop shows first two values stored in the Array. Next loop shows the whole value stored in the Array.

How to VB.Net NameValueCollection


NameValueCollection is used to store data like Name, Value format. It is very similar to Vb.Net HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold more than one value for a corresponding Key. Adding new pairs Add(ByVal name As String, ByVal value As String) Add("High","80") Get the value of corresponding Key GetValues(ByVal name As String) As String() String values() = GetValues("High") Download Source Code Print Source Code

Imports System.Collections.Specialized Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click Dim markStatus As New NameValueCollection Dim key As String Dim values() As String markStatus.Add("Very High", "80") markStatus.Add("High", "60") markStatus.Add("medium", "50") markStatus.Add("Pass", "40") For Each key In markStatus.Keys values = markStatus.GetValues(key) For Each value As String In values MsgBox(key & " - " & value) Next value Next key End Sub End Class

When you execute this source code , you will get each Key/Value sets.

Write Byte Array to a text file


The following VB.NET program shows how to write the content of a Byte Array into a Text file. Byte is an immutable value type that represents unsigned integers with values that range from 0 to 255 . Here we open a FileStream class instance and using the method Write() . Write() method writes a block of bytes to the current stream using data read from buffer.
oFileStream.Write(byteData, 0, byteData.Length)

Download Source Code


Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim str As String = "http://vb.net-informations.com" Dim encod As New System.Text.UTF8Encoding Dim byteData() As Byte = encod.GetBytes(str) Dim oFileStream As System.IO.FileStream oFileStream = New System.IO.FileStream("c:\bytes.txt", System.IO.FileMode.Create) oFileStream.Write(byteData, 0, byteData.Length) oFileStream.Close() End Sub End Class

String Array into a text file


An array is a data structure that contains multiple variables of the same type. Arrays helps us create shorter and simpler code in many situations. Arrays in VB.NET inherit from the Array class in the System namespace.
Dim months(11) As String

An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The default number of array elements is set to zero and the reference element is set to null. The elements of an array can be of any type, including an array type. The following VB.NET source code shows how to write the array content into a text file. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim months(11) As String months(0) = "Jan" months(1) = "Feb" months(2) = "Mar" months(3) = "Apr" months(4) = "May" months(5) = "Jun"

Print Source Code

months(6) = "Jul" months(7) = "Aug" months(8) = "Sep" months(9) = "Oct" months(10) = "Nov" months(11) = "Dec" System.IO.File.WriteAllLines("c:\file.txt", months) End Sub End Class

VB.NET STRING TUTORIALS

VB.NET STRING CLASS


The String Class represents character strings. The following sections describes , how to work with VB.NET String class . The String data type comes from the System.String class . The String type represents a string of Unicode Characters . The String class is a sealed class , so you cannot inherit another class from the String class. The String object is Immutable , it cannot be modified once it created, that means every time you use any operation in the String object , you create a new String Object . So if you are in a situation in continuous operation with String Object it is recommended to use System.Text.StringBuilder . System.Text.StringBuilder class to modify a string without creating a new object. In the following sections you can see the important methods in details with descriptions .

How to VB.NET String.Length()


The Length() function in String Class returned the number of characters occurred in a String. System.String.Length() As Integer Returns: Integer : The number of characters in the specified String

For ex: "This is a Test".Length() returns 14. Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "This is a Test" MsgBox(str.Length()) End Sub End Class

When you execute this source code you will get 17 in the messagebox.

How to VB.NET String.Insert()


The Insert() function in String Class will insert a String in a specified index in the String instance. System.String.Insert(Integer ind, String str) as String Parameters: ind - The index of the specified string to be inserted. str - The string to be inserted. Returns: String - The result string. Exceptions:

System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this instance System.ArgumentNullException : If the argument is null. For ex: "This is Test".Insert(8,"Insert ") returns "This is Insert Test" Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "This is VB.NET Test" Dim insStr As String = "Insert " Dim strRes As String = str.Insert(15, insStr) MsgBox(strRes) End Sub End Class

When you execute this program you will get the message box showing "This is VB.NET Insert Test"

How to VB.NET String.IndexOf()


The IndexOf method in String Class returns the index of the first occurrence of the specified substring. System.String.IndexOf(String str) As Integer Parameters: str - The parameter string to check its occurrences Returns:

Integer - If the parameter String occurred as a substring in the specified String it returns position of the first character of the substring . If it does not occur as a substring, -1 is returned. Exceptions: System.ArgumentNullException: If the Argument is null. For ex: "This is a test".IndexOf("Test") returns 10 "This is a test".IndexOf("vb") returns -1 Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" MsgBox(str.IndexOf("BOOKS")) End Sub End Class

When you execute this program you will get the number 14 in the message box. That means the substring "BOOKS" occurred and start in the position 14.

How to VB.NET String.Format()


VB.NET String Format method replace the argument Object into a text equivalent System.Striing.

System.Format(ByVal format As String, ByVal arg0 As Object) As String Parameters: String format : The format String The format String Syntax is like {indexNumber:formatCharacter} Object arg0 : The object to be formatted. Returns: String : The formatted String Exceptions: System.ArgumentNullException : The format String is null. System.FormatException : The format item in format is invalid. The number indicating an argument to format is less than zero, or greater than or equal to the number of specified objects to format. For ex : Currency : String.Format("{0:c}", 10) will return $10.00 The currency symbol ($) displayed depends on the global locale settings. Date : String.Format("Today's date is {0:D}", DateTime.Now)

You will get Today's date like : 01 January 2005 Time : String.Format("The current time is {0:T}", DateTime.Now) You will get Current Time Like : 10:10:12
Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim dNum As Double dNum = 32.123456789 MsgBox("Formated String " & String.Format("{0:n4}", dNum)) End Sub End Class

When you run this source code yo will get "Formated String 32.1234"

How to VB.NET String.Equals()


VB.NET String Equals function is to check the specified two String Object values are same or not System.String.Equals(String str1, String str2) As Boolean Parameters: String str1 : The String argument String str2 : The String argument Returns:

Boolean : Yes/No It return the values of the two String Objects are same For ex : Str1 = "Equals()" Str2 = "Equals()" String.Equals(Str1,Str2) returns True String.Equals(Str1.ToLower,Str2) returns False Because the String Objects values are different Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "Equals" Dim str2 As String = "Equals" If String.Equals(str1, str2) Then MsgBox("Strings are Equal() ") Else MsgBox("Strings are not Equal() ") End If End Sub End Class

When you run this program you will get message "Strings are Equal() "

How to VB.NET String.CopyTo()

VB.NET String CopyTo method Copies a specified number of characters from a specified position in this instance to a specified position in an array of characters. System.String.CopyTo(ByVal sourceIndex As Integer, ByVal destination() As Char, ByVal destinationIndex As Integer, ByVal count As Integer) Parameters: Integer sourceIndex : The starting position of the source String Char destination() : The character Array Integer destinationIndex : Array element in the destination Integer count : The number of characters to destination Exceptions: System.ArgumentNullException : If the destination is null System.ArgumentOutOfRangeException : Source Index, DestinationIndes or Count is a -ve value Count is greater than the length of the substring from startIndex to the end of this instance count is greater than the length of the subarray from destinationIndex to the end of destination Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "CopyTo() sample" Dim chrs(5) As Char

str1.CopyTo(0, chrs, 0, 6) MsgBox(chrs(0) + chrs(1) + chrs(2) + chrs(3) + chrs(4) + chrs(5)) End Sub End Class

When you run this Source code you will get CopyTo in MessageBox

How to VB.NET String.Copy()


VB.NET String Copy method is create a new String object with the same content System.String.Copy(ByVal str As String) As String Parameters: String str : The argument String for Copy method Returns: String : Returns a new String as the same content of argument String Exceptions: System.ArgumentNullException : If the argument is null. Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "VB.NET Copy() test" str2 = String.Copy(str1)

MsgBox(str2) End Sub End Class

When you run this source code you will get same content of str1 in str2

How to VB.NET String.Contains()


The Contains method in the VB.NET String Class check the specified parameter String exist in the String System.String.Contains(String str) As Boolean Parameters: String str - input String for search Returns: Boolean - Yes/No If the str Contains in the String then it returns true If the str does not Contains in the String it returns False For ex: "This is a Test".Contains("is") return True "This is a Test".Contains("yes") return False Exceptions: System.ArgumentNullException : If the argument is null

Download Source Code

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.Contains("TOP") = True Then MsgBox("The string Contains() 'TOP' ") Else MsgBox("The String does not Contains() 'TOP'") End If End Sub End Class

When you run the program you will get the MessageBox with message "The string Contains() 'TOP' "

How to VB.NET String.Compare()


The VB.NET String Compare function is use to compare two String Objects. System.String.Compare(String str1,String str2, Boolean ) As Integer It returns an Integer indication lexical relationship between the two comprehends Parameters: String str1 : Parameter String String str2 : Parameter String Boolean True/False Indication to check the String with case sensitive or without case sensitive Returns:

Integer : returns less than zero, zero or greater than zero. Less than zero : str1 is less than str2 zero : str1 is equal to str2 Greater than zero : str1 is grater than str2 Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "vb.net" str2 = "VB.NET" Dim result As Integer result = String.Compare(str1, str2) MsgBox(result) result = String.Compare(str1, str2, True) MsgBox(result) End Sub End Class

When you run this program first u get -1 in message box and then 0

How to VB.NET String.Clone()


The VB.NET String Clone() method returns a reference to this instance of String. Public Function Clone() As Object

Returns: Object : Return the instance of the String Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "Clone() Test" Dim clonedString As String clonedString = str.Clone() MsgBox(clonedString) End Sub End Class

When you run this program you ill get the same content of the first string "Clone() Test"

How to VB.NET String.Clone()


The VB.NET String Clone() method returns a reference to this instance of String. Public Function Clone() As Object Returns: Object : Return the instance of the String Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "Clone() Test" Dim clonedString As String clonedString = str.Clone()

MsgBox(clonedString) End Sub End Class

When you run this program you ill get the same content of the first string "Clone() Test"

How to VB.NET String.substring()


Substring in Vb.Net String Class returns a new string that is a substring of this string. The substring begins at the specified given index and extended up to the given length. Public Function Substring(ByVal startIndex As Integer, ByVal length As Integer) As String Parameters: startIndex: The index of the start of the substring. length: The number of characters in the substring. Returns: The specified substring. Exceptions: System.ArgumentOutOfRangeException : the beginIndex or length less than zero, or the begin index + length not within the specified string Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click

Dim str As String Dim retString As String str = "This is substring test" retString = str.Substring(8, 9) MsgBox(retString) End Sub End Class

When you execute this program , its will display "subtring" in the messagebox.

How to VB.NET String.Split()


Vb.Net String Split function returns an array of String containing the substrings delimited by the given System.Char array. Public Function Split(ByVal ParamArray separator() As Char) As String() Parameters: separator - the given delimiter Returns: An array of Strings delimited by one or more characters in separator Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ")

For count = 0 To strArr.Length - 1 MsgBox(strArr(count)) Next End Sub End Class

When you execute this programme , you will get "vb.net" "split" "test" in separate messagebox.

How to VB.NET String.EndsWith()


EndsWith in VB.NET String Class check if the Parameter String EndsWith the Specified String System.String.EndsWith(String suffix) as Boolean Parameters: suffix - The passing String for it EndsWith Returns: Boolean - Yes/No If the String EndsWith the Parameter String it returns True If the String doesnt EndsWith the Parameter String it return False For ex : "This is a Test".EndsWith("Test") returns True "This is a Test".EndsWith("is") returns False Exceptions:

System.ArgumentNullException : If the argument is null Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.EndsWith("BOOKS") = True Then MsgBox("The String EndsWith 'BOOKS' ") Else MsgBox("The String does not EndsWith 'BOOKS'") End If End Sub End Class

When you execute the program you will get a message box like "The String EndsWith 'BOOKS' "

How to VB.NET String.Concat()


Concat in VB.NET String Class using for concat two specified String Object System.String.Concat(ByVal str1 As String, ByVal str2 As String) As String String Concat method returns a new String Parameters: String str1 : Parameter String String str2 : Parameter String

Returns: String : A new String retrun with str1 Concat with str2 Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "Concat() " str2 = "Test" MsgBox(String.Concat(str1, str2)) End Sub End Class

When you run this source code you will get "Concat() Test " in message box.

How to String Title Case


Title Case converts the first character of a word to uppercase and the rest of the characters to lowercase. The CultureInfo class renders culture-specific information, such as the associated language, sublanguage, country/region, calendar, and cultural conventions.
System.Globalization.CultureInfo

A neutral culture is specified by only the two-letter lowercase language code. For example, "fr" specifies the neutral culture for French, and "de" specifies the neutral culture for German.
Dim cultureInfo As New System.Globalization.CultureInfo("en-US")

The String class indirectly uses this class to obtain information about the default culture. The follwoing VB.NET source code shows how to convert a string to Title Case.

Download Source Code


Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim _str As String Dim cultureInfo As New System.Globalization.CultureInfo("en-US") _str = cultureInfo.TextInfo.ToTitleCase("make first letter capital") MsgBox(_str) End Sub End Class

StringWriter and StringReader


StringWriter Class Implements a TextWriter for writing information to a string and the information is stored in an underlying StringBuilder Class. StringBuilder Class Represents a mutable string of characters and this class cannot be inherited. WriteLine(String) method writes a string followed by a line terminator to the text stream.
Dim stringWriter As New StringWriter() stringWriter.WriteLine("vb.net-informations.com")

StringReader Class Implements a TextReader that reads from a string. StringReader.ReadLine Method Reads a line from the underlying string.
Dim message As String Dim stringReader As New StringReader(String)

The next line from the underlying string, or Nothing if the end of the underlying string is reached. The following program shows how to use StringWriter and StringReader Classes in VB.NET.

Download Source Code


Imports System.IO Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stringWriter As New StringWriter() stringWriter.WriteLine("net-informations.com") stringWriter.WriteLine("vb.net-informations.com") stringWriter.WriteLine("csharp.net-informations.com") MsgBox(stringWriter.ToString) Dim singleLine As String Dim message As String Dim stringReader As New StringReader(stringWriter.ToString) While True singleLine = stringReader.ReadLine If singleLine Is Nothing Then Exit While Else message = message & singleLine & Environment.NewLine End If End While MsgBox(message) End Sub End Class

VB.NET Crystal Reports for Beginners


Start your first VB.NET Crystal Reports . All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Open Visual Studio .NET and select a new Visual Basic .NET Project.

Create a new Crystal Reports for Product table from the above database crystalDB. The Product Table has three fields (Product_id,Product_name,Product_price) and we are showing the whole table data in the Crystal Reports. From main menu in Visual Studio select PROJECT-->Add New Item . Then Add New Item dialogue will appear and select Crystal Reports from the dialogue box.

Select Report type from Crystal Reports gallery.

Accept the default settings and click OK. Next step is to select the appropriate connection to your database. Here we are going to select OLEDB connection for SQL Server Select OLE DB (ADO) from Create New Connection .

Select Microsoft OLE DB Provider for SQL Server .

Next screen is the SQL Server authentication screen . Select your Sql Server name , enter userid , password and select your Database Name . Click next , Then the screen shows OLE DB Property values , leave it as it is , and click finish. Then you will get your Server name under OLEDB Connection from there select database name (Crystaldb) and click the tables , then you can see all your tables from your database. From the tables list select Product table to the right side list .

Click Next Button Select all fields from Product table to the right side list .

Click Finish Button. Then you can see the Crystal Reports designer window . You can arrange the design according your requirements. Your screen look like the following picture.

Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form.

Select Form's source code view and put the code on top Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Reports is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. After you run the source code you will get the report like this.

Sample Database for running Crystal Reports tutorials


In the following section you can see , how to create a sample Database and Tables and data for running Crystal Reports Tutorials . All examples in the VB.NET Crystal Reports Tutorials are based on the following database . First we have to create a database . Give the database name as "crystaldb"

Create a DataBase "crystaldb" In the crystaldb database , create three tables OrderMaster , OrderDetails , Product . OrderMaster OrderMaster_id OrderMaster_date OrderMaster_customer OrderMaster_createduser OrderDetails OrderDetails_id OrderDetails_masterid OrderDetails_productid OrderDetails_qty Product Product_id Product_name Product_price

The following picture shows the relations of each table :

SQL command for creation tables are follows : CREATE TABLE [dbo].[OrderMaster] ( [OrderMaster_id] [int] NOT NULL , [OrderMaster_date] [datetime] NULL , [OrderMaster_customername] [varchar] (50), [OrderMaster_createduser] [varchar] (50) ) ON [PRIMARY]

CREATE TABLE [dbo].[OrderDetails] ( [OrderDetails_id] [int] NOT NULL , [OrderDetails_masterid] [int] NULL , [OrderDetails_productid] [int] NULL , [OrderDetails_qty] [int] NULL ) ON [PRIMARY] CREATE TABLE [dbo].[Product] ( [Product_id] [int] NOT NULL , [Product_name] [varchar] (50) , [Product_price] [numeric](18, 0) NULL ) ON [PRIMARY] Enter data to the tables : Order Master Table Data

Order Details Table Data

Product Table Data

VB.NET Crystal Reports from multiple tables


All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Here we are going to do is to generate Crystal Reports from multiple tables. Here we have three table (ordermaster , orderdetails amd product ) and we are generating report from these three tables by connecting each tables with their related fields. Open Visual Studio .NET and select a new Visual Basic .NET Project.

From main menu in Visual Studio select PROJECT-->Add New Item . Then Add New Item dialogue will appear and select Crystal Reports from the dialogue box.

Select Report type from Crystal Reports gallery.

Accept the default settings and click OK. Next step is to select the appropriate connection to your database. Here we are going to select OLEDB connection for SQL Server Select OLE DB (ADO) from Create New Connection .

Select Microsoft OLE DB Provider for SQL Server .

Next screen is the SQL Server authentication screen . Select your Sql Server name , enter userid , password and select your Database Name . Click next , Then the screen shows OLE DB Property values , leave it as it is , and click finish. Then you will get your Server name under OLEDB Connection from there select database name (Crystaldb) and click the tables , then you can see all your tables from your database.

Select all table from the table list to right side list box, because we are creating report from three tables ( OrderMaster, OrderDetails, Product) .

The next step is to make relation between these selected tables. Here we are connecting the related fields from each table. For that we arrange the tables in visible area in the list (this is not necessary ) and select the field we are going to make relation and drag to the related field of the other table. After made the relation the screen is look like the following picture .

Next step is to select the fields from the tables . Here we are selecting only Customername , orderdate from ordermastertable , Productname from product table and quantity from order details.

Click the Finish button because now we are not using other functionalities of this wizard. After that you will get the Crystal Reports designer window . You can arrange the fields in the designer window according to your requirement to view the report . For rearranging you can drag the field object in the screen . For editing right click the field object and select Edit Text Object. The following picture shows the sample of designer window after rearrange the field.

Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form.

Select Form's source code view and put the code on top Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. After you run the source code you will get the report like this.

Here we connected three tables related field and get the result . If you have any comments please contact the email address in our contact page.

VB.NET Crystal Reports String parameter

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Here we are passing a String parameter from vb.net to Crystal Reports . For that , from vb.net program we pass a customer name as parameter and show all the order of that customer to the Crystal Reports. In the previous tutorial we saw how to generate a Crystal Reports from multiple tables. Here is the continuation of that tutorial , the only different is that we are passing a Customer Name as a String parameter and get the report of that particular Customer only . Before starting to this tutorial just take a look at the previous tutorial ( Crystal Report from multiple tables ). In the previous section we are getting the report of all orders from all customers , that is the all order placed by all customers , here is only one customer. Hope you went through previous tutorial , if not click here ( Crystal Report from multiple tables ). Next step is to create a string parameter in Crystal report. Select the Field Explorer from CrystalReport Menu.

Then you can see Field Explorer in the Left hand side.

Select Parameter Field from Field Explorer and right Click.

Fill the appropriate name for Name and Promting text fields

After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD .

Then you can see the record Selection Formula Editor. This for entering the selection formula. For that you have to select the fields from above fields and make the formula . First you have to select OrderMaster.OrderMaster_customername from Report Field and select the comparison operator and select the parameter field. Double click each field then it will be selected. Form the following picture you can understand the selection fields.

After the creation of selection formula close that screen . Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and CrystalReportViewer control to your form.

Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")

Dim Dim Dim Dim

crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue

crParameterDiscreteValue.Value = TextBox1.Text crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Item("Customername") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Now you can run the program . Enter a Customer Name(enter any existing customer from Ordermaster table) and click the button , then your report is look like the following picture.

Here we get the result of the Customer4's order details.

VB.NET Crystal Reports Integer parameter


All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are passing an Integer Parameter to Crystal Reports from VB.NET.

In the previous tutorial , we saw passing a string parameter to Crystal Reports from VB.NET and get the result. This is very similar to that tutorial , so here showing only the change information part only. So please take a look at the complete part of passing a string parameter to Crystal Reports from VB.NET. When we pass an Integer parameter , we have to create a new Integer parameter in the Parameter Fields of Field Explorer. Then we will get the following screen and fill the fields like in the picture .

After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD . Then you can see the record Selection Formula Editor. This for entering the selection formula. For that you have to select the fields from above lists and make the formula .

Here we made the formula like select the records from Product table whose value is greater than the input value. For that first we select the table field that is Product_price from Product table and then we select the comparison operator and finally we select our Parameter we created earlier. Double click each field then it will automatically selected

After the creation of selection formula close that screen . Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and CrystalReportViewer control to your form. Select Form's source code view and import the following :

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue

crParameterDiscreteValue.Value = Convert.ToInt32(TextBox1.Text) crParameterFieldDefinitions = _ cryRpt.DataDefinition.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Item("Price") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES:

cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Now you can run the program . Enter any price , then you can see the report of the Product list whose price is greater than or equal to the entered price.

Here we got the result of Product list whose price is grater than 50.

VB.NET Crystal Reports Date parameter

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are passing a date variable to Crystal Reports from VB.NET. In the previous tutorials , we saw passing a string parameter to Crystal Reports , integer parameter to Crystal report from VB.NET and get the result. This tutorial is very similar to the above two tutorials , so please take look into the two tutorials before we start this one. When we pass a Date parameter, we have to create a new date parameter in the Parameter Fields of Field Explorer. Then we will get the following screen and fill the fields like in the picture .

After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD .

Then you can see the record Selection Formula Editor. This for entering the selection formula. For that you have to select the fields from above lists and make the formula . Here we are making the formula like , select all records details from the tables whose order date is greater than the input date parameter. For doing this you have to select Ordermaster.orderdate , comparison operator and parameter date field from selection list of Formula Editor and make the formula.

After the creation of selection formula close that screen . Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Report Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and CrystalReportViewer control to your form.

Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue

crParameterDiscreteValue.Value = TextBox1.Text crParameterFieldDefinitions = _ cryRpt.DataDefinition.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Item("Orderdate") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Now you can run the program . Enter any date , then you can see the report whose order date is greater than or equal to the entered date.

Here we got the result of orders whose date is greater than the entered date

VB.NET Crystal Reports Load Dynamically

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this section we are passing User ID , Password , Server Name and Database Name dynamically to Crystal Reports from vb.net . SITUATIONS : In many situations this is useful , for example if you develop a database project in a test server and later you have to migrate it , in such situations you have to give these information dynamically to Crystal Reports. In this program we are using our earlier program and pass the values dynamically to Crystal Reports. Before we start this section take a look at the step by step Crystal Report in VB.NET . In the step by step Crystal Report we created a report selecting all data from the Product table . There is no chance to change the server on runtime in that case because it is a static report . Here we are passing Server Name , UserID and Password dynamically to the Crystal Reports. Here we use Crystal Reports ConnectionInfo . Dim crConnectionInfo As New ConnectionInfo , and pass these arguments to ConnectionInfo Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code
Imports CrystalDecisions.CrystalReports.Engine

Print Source Code

Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument Dim crtableLogoninfos As New TableLogOnInfos Dim crtableLogoninfo As New TableLogOnInfo Dim crConnectionInfo As New ConnectionInfo Dim CrTables As Tables Dim CrTable As Table cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") With crConnectionInfo .ServerName = "YOUR SERVER NAME" .DatabaseName = "YOUR DATABASE NAME" .UserID = "YOUR DATABASE USERNAME" .Password = "YOUR DATABASE PASSWORD" End With CrTables = cryRpt.Database.Tables For Each CrTable In CrTables crtableLogoninfo = CrTable.LogOnInfo crtableLogoninfo.ConnectionInfo = crConnectionInfo CrTable.ApplyLogOnInfo(crtableLogoninfo) Next CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. You have to replace the source code values of "YOUR SERVER NAME" , "YOUR DATABASE NAME" , "YOUR DATABASE USERNAME" , "YOUR DATABASE PASSWORD" with your correct values .

When you run this program you will get the following screen.

VB.NET Crystal Reports Formula Fields


All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are adding a Formula Field in existing Crystal Reports . SITUATIONS :

If you have a Crystal Reports with Qty and Price , you need an additional field in your Crystal Reports for the Total of QTY X PRICE . In this situation you have to use the Formula Field in Crystal Reports. In this tutorial we are showing the all orders with qty and price and the total of each row , that means each in each row we are showing the total of qty and price. Before starting this tutorial. Create a new Crystal Reports with fields CustomerName , Order Date , Product Name and Product Price . If you do not know how to create this report , just look the previous tutorial Crystal Report from multiple tables . In that report selecting only four fields , here we need one more field Prodcut->Price . After you create the Crystal Reports you screen is look like the following picture :

Next is to create the a Formula Field for showing the total of Qty and Price . Right Click Formula Field in the Field Explorer and click New. Then you will get an Input Message Box , type Total in textbox and click Use Editor

Now you can see Formula Editor screen . Now you can enter which formula you want . Here we want the result of Qty X Price . For that we select OrderDetails.Qty , the multiplication operator and Product.Price . Double click each field for selection.

Now you can see Total Under the Formula Field . Drag the field in to the Crystal Reports where ever you want .

Now the designing part is over . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub

End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the following screen.

VB.NET Crystal Reports Summary Fields

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are taking the sum of field value of Total . This is the continuation of the previous tutorial Crystal Report Formula Field . So before we start this tutorial , take a look at the previous tutorial Crystal Report Formula Field. Here we are taking the grand total of the Total field . The Total field is a Formula field is the result of qty X price . In the Crystal Reports designer view right click on the Report Footer , just below the Total field and select Insert -> Summary .

Then you will get a screen , select the Total from the combo box and Sum from next Combo Box , and summary location Grand Total (Report Footer) . Click Ok button

Now you can see @Total is just below the Total field in the report Footer.

Now the designing part is over . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the following screen.

VB.NET Crystal Reports Export to PDF


Exporting from Crystal Reports to PDF format , we are using Crystal Reportss CrExportOptions . Also we have to set PdfRtfWordFormatOptions and ExportFormatType.PortableDocFormat . In the following example you can see how to export a Crystal Reports as a PDF format file. All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are using our earlier program step by step Crystal Report for pull data from database to Crystal Reports . Before we start this section take a look at the step by step Crystal Report in VB.NET . In the step by step Crystal Report we pull all data from Product table , here now we are exporting that data to a PDF format file. Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1, Button2 ) and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click events Download Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Dim cryRpt As New ReportDocument Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub

Print Source Code

Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions() CrDiskFileDestinationOptions.DiskFileName = _ "c:\crystalExport.pdf" CrExportOptions = cryRpt.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.PortableDocFormat .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With cryRpt.Export() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the PDF file (crystalExport.pdf) in your computer's C:

VB.NET Crystal Reports Export to Excel

Exporting from Crystal Reports to Excel format , we are using Crystal Reports CrExportOptions . Also we have to set ExcelFormatOptions and ExportFormatType.Excel . In the following example you can see how to export a Crystal Reports as a Excel format file. All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are using our earlier program step by step Crystal Report pull data from database to Crystal Reports . Before we start this section take a look at the step by step Crystal Report in VB.NET . In the step by step Crystal Report we pull all data from Product table , here now we are exporting that data to a Excel format file. Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1, Button2 ) and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click events Download Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Dim cryRpt As New ReportDocument Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _

Print Source Code

ByVal e As System.EventArgs) Handles Button2.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New ExcelFormatOptions CrDiskFileDestinationOptions.DiskFileName = _ "c:\crystalExport.xls" CrExportOptions = cryRpt.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.Excel .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With cryRpt.Export() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the Excel file (crystalExport.xls) in your computer's C:

Email a Crystal Reports from VB.NET


For Email a Crystal Reports , we have to export the Crystal Reports in any of the File Format available in Crystal Reports and then Email it.

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we use the tutorial Export Crystal Report to PDF file . So before we start this section please take a look at the tutorial Export Crystal Report to PDF file After export the Crystal Reports as a PDF file , the next step is to email that file . For that here we are using System.Web.Mail . We have to provide the necessary information to configuring SmtpMail client and send the exported file as attachment . Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1, Button2 ) and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Web.Mail Put the following source code in the button click events Download Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Web.Mail Public Class Form1 Dim cryRpt As New ReportDocument Dim pdfFile As String = "c:\ProductReport1.pdf" Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt

Print Source Code

CrystalReportViewer1.Refresh() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions CrDiskFileDestinationOptions.DiskFileName = pdfFile CrExportOptions = cryRpt.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.PortableDocFormat .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With cryRpt.Export() Catch ex As Exception MsgBox(ex.ToString) End Try sendMail() End Sub Private Sub sendMail() Try Dim Smtp As SmtpMail SmtpMail.SmtpServer.Insert(0, "your hostname") Dim Msg As MailMessage = New MailMessage Msg.To = "to address here" Msg.From = "from address here" Msg.Subject = "Crystal Report Attachment " Msg.Body = "Crystal Report Attachment " Msg.Attachments.Add(New MailAttachment(pdfFile)) Smtp.Send(Msg) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Before you run this programme , you have to provide the necessary SMTP informations , that is your HOSTNAME , FROM ADDRESS and TO ADDRESS to the SMTP client.

Crystal Reports Without Database


Usually Crystal Reports we are using to fetch data from database and show it as a report. Here we are going to generate a Crystal Reports without using a datbase . For generating a Crystal Reports without database , here we are using a Strongly Typed Dataset and a Data Table. The basics of Crystal Reports creation you can find in the previous section of this tutorial , before we start this tutorial you can take a look at the step by step Crystal Report. Generating a Strongly Typed DataSet Create a new VB.NET Project and accept the default settings. Create a new Dataset from Project - Add New Item Dialogue Box.

Accept the default name DataSet1.xsd . Create a data table for DataSet1.xsd . Select DataSet1.xsd from Solution Explorer and right click . Select datatable from the menu. Then you will get a datatable in the Datast . Right click the datatable and select Add-Column .

Here we are making a two column Crystal Reports , so we need two column in the data table . Add and ID column and Name column in the Data Table.

Now the dataset part is over . Next step is to create a Crystal Reports from this Dataset . Before going to make Crystal Reports design please take a look at step by step Crystal Report for easy creation of Crystal Reports. Select a new Crystal Reports from Add New Item menu and accept the default settings. The next screen is to select appropriate data source . There you can find the Datatable1 from Project data - ADO.NET Datasets , and select Datatable1 to the right side.

Click Next button and select ID and Name from the datatable1 to right side and click finish.

Now the Crystal Reports designer part is over . Next part is to create data for the Crystal Reports . For that we have to create a Data Table through programmatically and add data to dataset1. Select the default form (Form1.vb) you created in VB.NET and drag one button and CrystalReportViewer control to your form. Put the following source code in the button click events Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet1 Dim t As DataTable = ds.Tables.Add("Items") t.Columns.Add("id", Type.GetType("System.Int32")) t.Columns.Add("Item", Type.GetType("System.String")) Dim r As DataRow Dim i As Integer For i = 0 To 9 r = t.NewRow() r("id") = i r("Item") = "Item" & i t.Rows.Add(r) Next Dim objRpt As New CrystalReport1 objRpt.SetDataSource(ds.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1.Refresh() End Sub End Class

Crystal Reports from SQL Query String


We can create Crystal Reports in VB.NET using SQL Query String . Here we create a Strongly Typed dataset for Crystal Reports design and create a connection object and execute the SQL Query String . All Crystal Report programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure .

The basics of Crystal Reports creation you can find in the previous section of this tutorial , before we start this tutorial you can take a look at the step by step Crystal Report. Generating a Strongly Typed DataSet In the previous section you can see a detailed tutorial about to create a strongly typed datset and its Crystal Reports design . After create the dataset and Crystal Reports design you should create a connection object and fetch the data from database. Select the default form (Form1.vb) you created in VB.NET and drag one button and CrystalReportViewer control to your form. Put the following source code in the button click events Download Source Code Print Source Code

Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet1 Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=servername; _ initial catalog=crystaldb;user id=username;password=password;" cnn = New SqlConnection(connectionString) cnn.Open() sql = "SELECT Product_id,Product_name,Product_price FROM Product" Dim dscmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet1 dscmd.Fill(ds, "Product") MsgBox(ds.Tables(1).Rows.Count) cnn.Close()

Dim objRpt As New CrystalReport1 objRpt.SetDataSource(ds.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1.Refresh() End Sub End Class

NOTE : You have to provide the necessary databse information to Connection String.

Crystal Reports from SQL Query String


In usual practice , Crystal Reports we are getting from pre defined columns. But we can make Crystal Reports from Dynamic column . Here we are going to do the dynamic Crystal Reports from SQL statements . That is we enter SQL in textbox and get the Crystal Reports according to the SQL statement.

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Create a new VB.NET project and add a Strongly Typed Dataset . Before creating a Strongly Typed take a look at the detailed tutorial of create a strongly typed datset and add five column in the Datatable. Here we are limiting as five column , but you can add any number of column according to your requirements.

Next step is to create a Crystal Reports design from the Strongly Typed dataset.

Select all the column from dataset.

Select the default form(Form1.vb) and add a TextBox , Button and Crystal Reports Viewer . Here we are going to pass the SQl statements to Crystal Reports at runtime . For that we parsing the SQL statement before we passing it to Crystal Reports. So we create a function for parsing SQL statements. Public Function procesSQL() As String Put the following vb.net source code in your form and run the program .

Download Source Code

Print Source Code

Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Data Public Class Form1 Dim objRpt As New CrystalReport1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=SERVERNAME; _ initial catalog=crystaldb;user id=sa;password=PASSWORD;" cnn = New SqlConnection(connectionString) cnn.Open() sql = procesSQL() Dim dscmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet1 dscmd.Fill(ds, "Product") objRpt.SetDataSource(ds.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1.Refresh() End Sub Public Function procesSQL() As String Dim sql As String Dim inSql As String Dim firstPart As String Dim lastPart As String Dim selectStart As Integer Dim fromStart As Integer Dim fields As String() Dim i As Integer Dim MyText As TextObject inSql = TextBox1.Text inSql = inSql.ToUpper selectStart = inSql.IndexOf("SELECT")

fromStart = inSql.IndexOf("FROM") selectStart = selectStart + 6 firstPart = inSql.Substring(selectStart, (fromStart - selectStart)) lastPart = inSql.Substring(fromStart, inSql.Length - fromStart) fields = firstPart.Split(",") firstPart = "" For i = 0 To fields.Length - 1 If i > 0 Then firstPart = firstPart & " , " _ & fields(i).ToString() & " AS COLUMN" & i + 1 MyText = CType(objRpt.ReportDefinition.ReportObjects("Text" _ & i + 1), TextObject) MyText.Text = fields(i).ToString() Else firstPart = firstPart & fields(i).ToString() & _ " AS COLUMN" & i + 1 MyText = CType(objRpt.ReportDefinition.ReportObjects("Text" & _ i + 1), TextObject) MyText.Text = fields(i).ToString() End If Next sql = "SELECT " & firstPart & " " & lastPart Return sql End Function End Class

NOTE : You have to provide the necessary databse information to Connection String.

Crystal Reports from XML File

In this section you can see , creating a Crystal Reports from XML file instead of database . This is very similer to creating Crystal Reports from database , the only difference is to sslect the data source as your XML file. Here we are creating an XML file name is Product is XML file the same structure of the Product table in the sample Database Structure. Download Product.XML

The basics of Crystal Reports creation provided in previous tutorials , if you dont have much knowledge in Crystal Reports , take a look at the tutorial step by step Crystal Report before start this section. The change happen only from previous report , when you select Data for Crsyatl Report , you have to select Create New Connection Database Files and select the XML file you want to generate Crystal Reports (In this case you select the Product.xml ).

Select all the fields from Product and click finish button

Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here.

Create a Subreport in Crystal Reports


Subreport in Crystal Reports means a Report within a Report . When we want to show some additional information about the data in the Crystal Reports , we use the subreports to show the details. Subreports we show within the main Crystal Reports and also we can show it as On-Demand report , that means we put an Hyper link in the row, and when user click that hyper link then will get the subreport. This section we are showing the subreport within the Crystal Reports . That is for each row there is a subreoprt for the details.

All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Here we are create an order report based on three tables in the database and show a subreoprt for each row of the specified Product Name. Here we are using our earlier program Crystal Report from multiple tables to show the main Crystal Reports Data , so please refer Crystal Report from multiple tables before start this section . Create a Crystal Reports using three tables and select customername , date , product and qty . It will explain in detail the previous section Crystal Report from multiple tables .

Next step is to create a subreport inside the main report. Here we are showing the Product details in each row of the specified product in the main row. After create the main report , right click on Crystal Reports designer window and select Insert-Subreport.

Then you will get the subreport object , drag the object in the designer window at the down part of the details tab , just below the fields in the details tab. When you release the mouse you will get a dialogue box asking report name . Enter the report name you want and click the Report Wizard button. The wizard shows the table selection screen and select the table . Here in this case we are selecting the Product Table from the list and click next . Next screen is showing the table , from there select the fields you want to show the data and click finish. The you will get the subreport main screen again and select Link tab . The link tab is making relation with your main Report and subreport . Here we are linking the productname from main report to the subreport. For that select Product.Product_name from Available fields.

Accept the other settings as it is in the screen and click ok. Now you can see the subreport object in the screen , if you want to modify subreport design , double click on subreport object and you can design subreport.

Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim crp As New CrystalReport1 CrystalReportViewer1.ReportSource = crp CrystalReportViewer1.Refresh() End Sub End Class

Create a Subreport in Crystal Reports with Link

In the previous section Subreport in Crystal Report is described how to insert a subreport in Crystal Reports . In that case the subreport is embedded within the main Crystal Reports. Here we are creating a subreport , and the subreport has only a link in the main Report , on-demand subreports . That is when the user click the link , then only the subreport display.

Here we are using our previous example Subreport in Crystal Report and make a link in the min Crystal Reports for on-demand subreport. Select the subreport object in the Crystal Reports and right click , then select Format Object .

Then you will get Format Editor . Select Subreport tab from Format Editor , you can find there a check box On-demand Subreport . You have to select that check box , then the subreport become as a link in your main Crystal Reports. If you want to change the title , you can change it in subreport name textbox. Finally click OK button.

Now the designing part is over and you are ready to generate subreport on-demand. Next step is to select the default form(Form1.vb) and add a Button and Crystal Report Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim crp As New CrystalReport1 CrystalReportViewer1.ReportSource = crp CrystalReportViewer1.Refresh() End Sub End Class

How to deploy Crystal Reports on Clinet Machine


Crystal Reports for Visual Studio ships with your deployment projects that enable you to deploy Crystal Reports components and assemblies on the target machine. We can use different approaches to install Crystal Reports runtime files on the target machine . If you are using Visual Studio then during your setup and deployment you can add the CRRedist2005_x86.msi file to your setup file and distribute it as a single setup file . The installer can execute the setup file automatically with your .Net Project in a single click. You can find the CRRedist2005_x86.msi file in your system's C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports . Also you can distribute the CRRedist2005_x86.msi separately and install it on the target machine. The other way to install Crystal Reports on target machine is to create a setup file using Merge Modules and distribute it with your application or as a separate setup file. Click the following link to see how to make a setup file with Merge Modules.

How to create Crystal Reports installer using Merge Modules


Crystal Reports uses merge modules to ensure the correct report components and assemblies are installed with your deployment project. A merge module is a set of components that are merged with a Windows installer for applications that need them. The following steps are creating a setup file for Crystal Reports Client side installation using Merge Modules. Before creating a setup project, make sure that the following files exist in the \Program Files\Common Files\Merge Modules folder. CrystalReportsRedist2005_x86.msm Microsoft_VC80_ATL_x86.msm policy_8_0_Microsoft_VC80_ATL_x86.msm

Steps to create Setup file. 1) Make sure the above mentioned files are in the \Program Files\Common Files\Merge Modules folder , If the files are not there you can download the file and copy it to the folder \Program Files\Common Files\Merge Modules . Download: https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/11688 2) Open your Visual Studio 3) Select "New Project" from File menu.

4) Select "Setup and Deployment" from "Other Project Types" 5) In the "Solution Explorer", select your setup project, right-click, and select Add and Merge Module from the menu.

6) Select CrystalReportsRedist2005_x86.msm to your setup project. The file available at \Program Files\Common Files\Merge Modules

Then you can see Microsoft_VC80_ATL_x86.msm and policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically added in the Detected Depencies section. 7) Build your project. Now you will get the setup file for distribution. Either you can add this setup file to you application installer or distribute it as a separate setup file.

Microsoft .Net Framework Framework Tutorials


The .NET Framework is Microsoft's Managed Code programming model for building applications on Windows clients, servers, and mobile or embedded devices. Microsoft's .NET Framework is a software technology that is available with several Microsoft Windows

operating systems. In the following sections describes , the basics of Microsoft .Net Frame work Technology and its related programming models.

How to Microsoft .Net Framework


Microsoft .Net Languages Source Code are compiled into Microsoft Intermediate Language (MSIL) . MSIL we can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). Microsoft Intermediate Language (MSIL) is a CPU independent set of instructions that can be converted to the native code. Metadata also created in the course of compile time with Microsoft Intermediate Language (MSIL) and stored it with the compiled code . Metadata is completely self-describing . Metadata is stored in a file called Manifest, and it contains information about the members, types, references and all the other data that the Common Language Runtime (CLR) needs for execution .

The Common Language Runtime (CLR) uses metadata to locate and load classes, generate native code, provide security, and execute Managed Code. Both Microsoft Intermediate Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file. Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by Microsoft .Net Framework. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. The native code is Operating System independent and this code is known as Managed Code , that is, the language's functionality is managed by the .NET Framework . The Common Language Runtime (CLR) provides various Just In Time (JIT) compilers, and each works on a different architecture depends on Operating Systems, that means the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems. In the following section you can see how Common Language Runtime (CLR) functions .

What is Microsoft .Net Framework


The Microsoft .Net Framework is a platform that provides tools and technologies you need to build Networked Applications as well as Distributed Web Services and Web Applications. The .Net Framework provides the necessary compile time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).The main two components of .Net Framework are Common Language Runtime (CLR) and .Net Framework Class Library (FCL).

The Common Language Runtime (CLR) is the runtime environment of the .Net Framework , that executes and manages all running code like a Virtual Machine. The .Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes. The .Net Framework Class Libraries (FCL) are arranged into a logical grouping according to their functionality and usability is called Namespaces. In the following sections describes how to .Net Framework manages the code in compile time and run time .

Common Language Runtime

The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS). The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. The Managed Code compiled only when it needed, that is it converts the appropriate instructions when each function is called . The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time. During the execution of the program ,the Common Language Runtime (CLR) manages memory, Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS), code safety verifications, and other system services. The CLR ( Common Language Runtime ) defines the Common Type System (CTS), which is a standard type system used by all .Net languages . That means all .NET programming languages uses the same representation for common Data Types , so Common Language Runtime (CLR) is a language-independent runtime environment . The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System. In the coming section you can see what are the main functions of Common Language Runtime (CLR).

How to Common Language Runtime


The Common Language Runtime (CLR) is a an Execution Environment . Common Language Runtime (CLR)'s main tasks are to convert the .NET Managed Code to native code , manage running code like a Virtual Machine and also controls the interaction with the Operating System. Common Language Runtime (CLR) manages Thread executions, Memory Management that is allocation of Objects and Buffers , Garbage Collection (GC) - Clean up the unused Objects and buffers , Exception Handling, Common Type System (CTS) that is all .NET language that conforms to the Common Language Specification (CLS) have the same primitive Data Types, Code safety verifications - code can be verified to ensure type safety, Language integration that is Common Language Runtime (CLR) follow a set of specification called Common Language Specification (CLS) , this will ensure the interoperability between languages, Integrated security and other system services.

.Net Framework Class Library (FCL)

The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture . The .Net Framework Class Library (FCL) includes a huge collection of reusable classes , interfaces, and value types that expedite and optimize the development process and provide access to system functionality. The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.

Common Language Specification


Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services , which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages , those objects must expose the features that are common to all the languages . Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application. Common Language Specification (CLS) defines a subset of Common Type System (CTS) . Common Type System (CTS) describes a set of types that can use different .Net languages have in common , which ensure that objects written in different languages can interact with each other. Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) standardized by ECMA .

Common Type System


Common Type System (CTS) describes a set of types that can be used in different .Net languages in common . That is , the Common Type System (CTS) ensure that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level . These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in

any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.

Portable Executable (PE) File Format


The Portable Executable (PE) format is a file format for executables, object code, and DLLs, used in 32-bit and 64-bit versions of Windows operating systems. The PE file format was defined to provide the best way for the Windows Operating System to execute code and also to store the essential data which is needed to run a program. Portable Executable File Format is derived from the Microsoft Common Object File Format (COFF).

Just In Time Compiler


The .Net languages , which is conforms to the Common Language Specification (CLS), uses its corresponding runtime to run the application on different Operating Systems . During the code execution time, the Managed Code compiled only when it is needed, that is it converts the appropriate instructions to the native code for execution just before when each function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic Translation . With the help of Just In Time Compiler (JIT) the Common Language Runtime (CLR) doing these tasks. The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each works on a different architecture depending on Operating System. That is why the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems without rewrite the source code. Just In Time (JIT) compilation preserves memory and save time during application initialization. Just In Time (JIT) compilation is used to run at high speed, after an initial phase of slow interpretation. Just In Time Compiler (JIT) code generally offers far better performance than interpreters.

Managed Code

Managed Code in Microsoft .Net Framework, is the code that has executed by the Common Language Runtime (CLR) environment. On the other hand Unmanaged Code is directly executed by the computer's CPU. Data types, error-handling mechanisms, creation and destruction rules, and design guidelines vary between managed and unmanaged object models. The benefits of Managed Code include programmers convenience and enhanced security . Managed code is designed to be more reliable and robust than unmanaged code , examples are Garbage Collection , Type Safety etc. The Managed Code running in a Common Language Runtime (CLR) cannot be accessed outside the runtime environment as well as cannot call directly from outside the runtime environment. This makes the programs more isolated and at the same time computers are more secure . Unmanaged Code can bypass the .NET Framework and make direct calls to the Operating System. Calling unmanaged code presents a major security risk.

.Net Assembly
Microsoft .Net Assembly is a logical unit of code, it contains code that the Common Language Runtime (CLR) executes. Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. During the compile time Metadata is created, with Microsoft Intermediate Language (MSIL), and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. Manifest contains information about itself. This information is called Assembly Manifest, it contains information about the members, types, references and all the other data that the runtime needs for execution. Every Assembly you create contains one or more program files and a Manifest. There are two types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only one entry point (that is, DllMain, WinMain, or Main). We can create two types of Assembly, private Assembly and shared Assembly . A private Assembly is used only by a single application, and usually it is stored in that application's install directory. A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).

Global Assembly Cache (GAC)


Each computer on which the Common Language Runtime is installed has a machine-wide code cache called the 'Global Assembly Cache'. The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications.

The GAC is automatically installed with the .NET runtime. The global assembly cache is located in 'Windows/WinNT' directory and inherits the directory's access control list that administrators have used to protect the folder. The approach of having a specially controlled central repository addresses the shared library concept and helps to avoid pitfalls of other solutions that lead to drawbacks like DLL hell. The Global Assembly Cache Tool (Gacutil.exe), that allows you to view and manipulate the contents of the Global Assembly Cache.

What is a Satellite Assembly?


A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user selects to view the application in that language. In general, assemblies should contain culture-neutral resources. If you want to localize your assembly (for example use different strings for different locales) you should use satellite assemblies. Use the Assembly Linker (Al.exe) to compile .resources files into satellite assemblies. Al.exe creates an assembly from the .resources files that you specify. By definition, satellite assemblies can only contain resources. They cannot contain any executable code.

What are the contents of an Assembly?


A .NET static assembly can consist of following elements: a) Assembly Manifest - The Metadata that describes the assembly and its contents b) Type Metadata - Defines all types, their properties and methods. c) MSIL - Microsoft intermediate language d) A set of Resources - All other resources like icons, images etc. Only the assembly manifest is required, but either types or resources are needed to give the assembly in any meaningful functionality.

Private Assembly and Shared Assembly

A private assembly is an assembly that is available to particular application where they are kept, and a Shared Assembly is a public assembly that is shared by multiple applications. That means, a Private Assembly cannot be references outside the scope of the folder where they are kept and a Shared Assembly is one that can be referenced by more than one application. In order to share an assembly, the assembly must be explicitly built for this purpose by giving it a cryptographically strong name . By contrast, a private assembly name need only be unique within the application that uses it. The classes that ship with the .NET Framework are all built as shared assemblies.

What is .Net Strong Name


Strong name consists of an Assemblys identity, that means the Assemblies can be assigned a cryptographic signature. The strong name guarantees the integrity of the assembly which prevents someone from taking over the name of the assembly. Strong Name includes the name of the .net assembly, version number, culture identity, and a public key token. It is generated from an assembly file using the corresponding private key. Strong names guarantee name uniqueness by relying on unique key pairs. To create a key pair At the command prompt, type the following command: sn -k fileName In this command, file name is the name of the output file containing the key pair.

.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification. The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET

Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.

Application Domain
An application domain is a virtual process and is used to isolate applications from one another. Each application domain has their own virtual address space which scopes the resources for the application domain using that address space. Each application running within its main process boundaries and its application domain boundaries. All objects created within the same application scope are created within the same application domain. Multiple application domains can exist in a single operating system process. An application running inside one application domain cannot directly access the code running inside another application domain. System.AppDomain is the main class you can use to deal with application domains.

Code Access Security


The .NET Security Model provides code access permissions and code identity permissions. Code Access Security is the part of the .NET security model that determines whether or not the code is allowed to run, and what resources it can use when it is running. Code Access Security policy uses evidence to help grant the right permissions to the right assembly. An administrator can configure Code Access Security policy to restrict the resource types that code can access and the other privileged operations it can perform. Code Access Security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code.

Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the

application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap. The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.

Threads
Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance. Multithreading allows multiple process to execute concurrently within a single program .That is more than one task in a program can execute at the same time and each thread run independently of its own. If multiple threads can exist within a process, typically share the state information of a process, and share memory and other resources directly. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled. In multiple threaded programming we can use system's idle time, so it leads improved application performance . Also we can set priority in each Threads . Threads with higher priority are executed in preference to threads with lower priority. It is recommended that you use as few threads as possible, thereby minimizing the use of Operating System resources . Check the following links to see how Multi Threaded applications works in VB.NET . 1. Multithreaded Socket Programming 2. Multi Threaded Chat Server Program

VB.NET MultiThreaded Socket Programming

Multithreaded Socket Programming means that a Multithreaded Server can communicate with more than one clients at the same time . In the previous section Socket Programming , the Server Socket Program can communicate with only one client at a time . That means it s not possible to connect another Client Socket Program at the same time to communicate with Server . From the following figure you can understand how to a Server can communicate with more than one client at the same time .You can see the basics of Socket Programming in the previous section , take a look at Socket Programming before you start this section.

The basic idea behind Multithreaded Socket Programming is, whenever Server gets a connection request from Client , the Server create a separate ( independent ) Thread for the each Client request. That means for each Client, there is a separate Client Thread in Server . So the Client can communicate independently with their own Client Thread in Server.

In the following sections you can see in detail of How a Multithreaded Socket Programming can communicate with more than one client at the same time. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program How to run this program ? Create Multithreaded Server Socket Program and Multithreaded Client Socket Program and run the Server program first . Then you will get message of "Server started" . Next you start the Client program , then you can see the message from Server . You can start

more than one client same time and communicate with Server . For each client Server responds with the Clients Connection ID Number.

How to send email from VB.NET


VB.NET using SMTP protocol for sending email . SMTP stands for Simple Mail Transfer Protocol . VB.NET using System.Net.Mail namespace for send mail . We can instantiate SmtpClient class and assign the Host and Port . The default port using SMTP is 25 , but it may vary different Mail Servers .In the following example shows how to send an email from a Gmail address. The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 . Here using NetworkCredential for password based authentication. Download Source Code Print Source Code

Imports System.Net.Mail Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim SmtpServer As New SmtpClient() Dim mail As New MailMessage() SmtpServer.Credentials = New _ Net.NetworkCredential("username@gmail.com", "password") SmtpServer.Port = 587 SmtpServer.Host = "smtp.gmail.com" mail = New MailMessage() mail.From = New MailAddress("YOURusername@gmail.com") mail.To.Add("TOADDRESS") mail.Subject = "Test Mail" mail.Body = "This is for testing SMTP mail from GMAIL" SmtpServer.Send(mail) MsgBox("mail send") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

You have to provide the informations like your gmail username and password , and the to address also.

VB.NET Send email using CDOSYS


Using CDOSYS is another easy way to send email from VB.NET . For sending email using CDOSYS , you have to send email from Windows 2000/XP and also you have to be enabled SMTP Service in IIS . Requirements
Windows XP/ Windows2000 Internet Information Services (IIS) SMTP Services in IIS should be enable.

Download Source Code

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim CDOSYS As Object Const cdoSendUsingPickup = 1 Const strPickup = "c:\inetpub\mailroot\pickup" CDOSYS = CreateObject("CDO.Message") CDOSYS.Configuration.Fields.item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") _ = cdoSendUsingPickup CDOSYS.Configuration.Fields.item _ ("http://schemas.microsoft.com/cdo/configuration" & _ /smtpserverpickupdirectory") _ = strPickup CDOSYS.Configuration.Fields.Update() CDOSYS.To = "TO ADDRESS" CDOSYS.From = "FROM ADDRESS" CDOSYS.Subject = "CDO Test" CDOSYS.TextBody = "Send Email from vb.net using CDOSYS"

CDOSYS.Send() CDOSYS = Nothing MsgBox("mail send") End Sub End Class

You have to provide the informations like To Address , From Address and it is very important to enable your SMTP services in IIS .

How to find IP Address of Host


Syste.net namespace provide the infomation about IP Address .

If you pass localhost in GetHostByName return the IP Address of local machine . Download Source Code Print Source Code

Imports System.Net Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim hostname As IPHostEntry = Dns.GetHostByName(TextBox1.Text) Dim ip As IPAddress() = hostname.AddressList TextBox2.Text = ip(0).ToString() End Sub End Class

How to read a URL Content


When we want to read content of an HTML page from a remote webserver , in vb.net we are using WebRequest , WebResponse . WebResponse return a StreamReader and we can retrieve the content using a StreamReader.

Download Source Code

Print Source Code

Imports System.Net Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim inStream As StreamReader Dim webRequest As WebRequest Dim webresponse As WebResponse webRequest = webRequest.Create(TextBox1.Text) webresponse = webRequest.GetResponse() inStream = New StreamReader(webresponse.GetResponseStream()) TextBox2.Text = inStream.ReadToEnd() End Sub End Class

VB.NET Socket Programming


A Socket is an End-Point of To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the network . We need two programs for running a socket program. A Server Socket Program ( Server ) and a Client Socket Program ( Client ) . Server Program: A Server Socket Program running on a computer has a socket that bound to a Port Number on that computer and listening to the client's requests. Client Program: Client Socket Program have to know the IP Address ( Hostname ) of the computer that the Server Socket Program resides and the Port Number assign for listening for client's request .

Once the communication is established , the Server and Client can read or write their own sockets. There are two types of communication protocol use for Socket Programming TCP/IP ( Transmission Control Protocol/Internet protocol ) Communication and UDP/IP ( User Datagram Protocol/Internet protocol ) Communication . In the following section we are going to communicate a Server Socket Program and Client Socket Program through VB.NET using TCP/IP Communication.

In the above picture shows the communication interfaces . Server Socket Program: Here Server Socket Program is done through a Console based VB.NET application . Here the Server listening for the client's request , and when the server get a request from the Client , Server sends the response to Client . Click the following link to see in detail of a Server Socket Program .

Client Socket Program: The Client Socket Program is a windows based application . When the client start its get connect the server and send requests , and also receive the response from Server . Click the following link to see in detail of Client Socket Program. How to run this program ? The Socket Programming has two sections. 1. Server Socket Program 2. Client Socket Program When you finish coding the program , First you have to start Server Socket Program , then you will get the DOS screen with a message Server Started . Next step is to start Client Socket Program . Then you will get message in client screen Client Started , at the same time you check with server screen a message Accept connection from client . Now your Server Socket Program and Client Socket Program get connected . If you want to test the communication , you click the button ( Click here to send data to Server ) in client window , then you can see changes in Server and Client screen messages .

VB.NET Server Socket Program

The Socket Programming has two sections. 1. Server Socket Program 2. Client Socket Program The Server Socket Program here is a VB.NET Console based Application . This program act as a Server and listening to clients request . We assign Port 8888 for the Server Socket , it is an instance of the VB.NET Class TcpListener , and call its start() method.
Dim serverSocket As New TcpListener(8888) serverSocket.Start()

Next step we are creating an infinite loop for continuous communication to Client . When Server get the request , it reads the data from NetworkStream and also write the response to NetworkStream . Create a new VB.NET Console Application Project and put the following source code into project.

Download Source Code


Imports System.Net.Sockets Imports System.Text Module Module1 Sub Main() Dim serverSocket As New TcpListener(8888) Dim requestCount As Integer Dim clientSocket As TcpClient serverSocket.Start() msg("Server Started") clientSocket = serverSocket.AcceptTcpClient() msg("Accept connection from client") requestCount = 0

Print Source Code

While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() Dim bytesFrom(10024) As Byte networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) Dim dataFromClient As String = _ System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _ dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("Data from client - " + dataFromClient) Dim serverResponse As String = _ "Server response " + Convert.ToString(requestCount) Dim sendBytes As [Byte]() = _ Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.ToString) End Try End While clientSocket.Close()

serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub End Module

The next part of this section is Client Socket Program . After create the Client Socket Program , you should first start the Server Socket Program and then start the Client Socket Program . If you need more details about this tutorial please refer to Socket Programming Section .

VB.NET Client Socket Program

The Socket Programming has two sections.

1. Server Socket Program 2. Client Socket Program The Client Socket Program is the continuation of the Server Socket Program . The Client Socket Program is a Windows based application . Client connect to the Port 8888 of the Server Socket Program , and the IP Address (Computer Name) here we give as 127.0.0.1 , because the Server and client running on the same machine . clientSocket.Connect("127.0.0.1", 8888) When client gets connected , it reads data from NetworkStream , and also write to NetworkStream . When you start the client program you will get message client started . When press the button at the bottom its send a message to Server and also receive a message from Server. Download Source Code Print Source Code

Imports System.Net.Sockets Imports System.Text Public Class Form1 Dim clientSocket As New System.Net.Sockets.TcpClient() Dim serverStream As NetworkStream Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim serverStream As NetworkStream = clientSocket.GetStream() Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes("Message from Client$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim inStream(10024) As Byte serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize)) Dim returndata As String = _ System.Text.Encoding.ASCII.GetString(inStream) msg("Data from Server : " + returndata) End Sub Private Sub Form1_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load msg("Client Started") clientSocket.Connect("127.0.0.1", 8888) Label1.Text = "Client Socket Program - Server Connected ..." End Sub Sub msg(ByVal mesg As String) TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg End Sub End Class

Brfore you run the Client Socket Program you should start Server Socket Program first . For more details of running this program , take a look at the VB.NET Socket Programming .

VB.NET MultiThreaded Socket Programming


Multithreaded Socket Programming means that a Multithreaded Server can communicate with more than one clients at the same time . In the previous section Socket Programming , the Server Socket Program can communicate with only one client at a time . That means it s not possible to connect another Client Socket Program at the same time to communicate with Server . From the following figure you can understand how to a Server can communicate with more than one client at the same time .You can see the basics of Socket Programming in the previous section , take a look at Socket Programming before you start this section.

The basic idea behind Multithreaded Socket Programming is, whenever Server gets a connection request from Client , the Server create a separate ( independent ) Thread for the each Client request. That means for each Client, there is a separate Client Thread in Server . So the Client can communicate independently with their own Client Thread in Server.

In the following sections you can see in detail of How a Multithreaded Socket Programming can communicate with more than one client at the same time. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program How to run this program ? Create Multithreaded Server Socket Program and Multithreaded Client Socket Program and run the Server program first . Then you will get message of "Server started" . Next you start the Client program , then you can see the message from Server . You can start

more than one client same time and communicate with Server . For each client Server responds with the Clients Connection ID Number.

VB.NET MultiThreaded Server Socket Programming


MultiThreaded Server Socket Program here is a VB.NET Console based application , that can handle multiple clients at the same time. You can see the basics of Socket Programming in the previous section , take a look at Socket Programming before you start this section. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program Here we create a Server Socket from TcpListener class and listen to PORT 8888 . When the server gets a request from Client , the Server pass the instance of the client request to a separate class handleClient . In handleClient class there is a Thread , handling the communication between the instance of Server side client and Client from outside . For each request , in Server there is a new thread instant is create for communication , so we can connect more than one client at the same time to Server and communicate independently . Create a new VB.NET Console Application project and put the following source code in the project. Download Source Code
Imports System.Net.Sockets Imports System.Text Module Module1 Sub Main() Dim serverSocket As New TcpListener(8888) Dim clientSocket As TcpClient Dim counter As Integer

Print Source Code

serverSocket.Start() msg("Server Started") counter = 0 While (True) counter += 1 clientSocket = serverSocket.AcceptTcpClient() msg("Client No:" + Convert.ToString(counter) + " started!") Dim client As New handleClinet client.startClient(clientSocket, Convert.ToString(counter)) End While clientSocket.Close() serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Public Sub startClient(ByVal inClientSocket As TcpClient, _ ByVal clineNo As String) Me.clientSocket = inClientSocket Me.clNo = clineNo Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat) ctThread.Start() End Sub Private Sub doChat() Dim requestCount As Integer Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim sendBytes As [Byte]() Dim serverResponse As String Dim rCount As String requestCount = 0

While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _ dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("From client-" + clNo + dataFromClient) rCount = Convert.ToString(requestCount) serverResponse = "Server to clinet(" + clNo + ") " + rCount sendBytes = Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.ToString) End Try End While End Sub End Class End Module

The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program You have to run Server program first and then Client program , then only you can communicate with Server and Client each other .

VB.NET MultiThreaded Server Socket Programming

MultiThreaded Server Socket Program here is a VB.NET Console based application , that can handle multiple clients at the same time. You can see the basics of Socket Programming in the previous section , take a look at Socket Programming before you start this section. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program Here we create a Server Socket from TcpListener class and listen to PORT 8888 . When the server gets a request from Client , the Server pass the instance of the client request to a separate class handleClient . In handleClient class there is a Thread , handling the communication between the instance of Server side client and Client from outside . For each request , in Server there is a new thread instant is create for communication , so we can connect more than one client at the same time to Server and communicate independently . Create a new VB.NET Console Application project and put the following source code in the project. Download Source Code
Imports System.Net.Sockets Imports System.Text Module Module1 Sub Main() Dim serverSocket As New TcpListener(8888) Dim clientSocket As TcpClient Dim counter As Integer serverSocket.Start() msg("Server Started") counter = 0 While (True) counter += 1 clientSocket = serverSocket.AcceptTcpClient() msg("Client No:" + Convert.ToString(counter) + " started!") Dim client As New handleClinet

Print Source Code

client.startClient(clientSocket, Convert.ToString(counter)) End While clientSocket.Close() serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Public Sub startClient(ByVal inClientSocket As TcpClient, _ ByVal clineNo As String) Me.clientSocket = inClientSocket Me.clNo = clineNo Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat) ctThread.Start() End Sub Private Sub doChat() Dim requestCount As Integer Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim sendBytes As [Byte]() Dim serverResponse As String Dim rCount As String requestCount = 0 While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _

dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("From client-" + clNo + dataFromClient) rCount = Convert.ToString(requestCount) serverResponse = "Server to clinet(" + clNo + ") " + rCount sendBytes = Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.ToString) End Try End While End Sub End Class End Module

The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program You have to run Server program first and then Client program , then only you can communicate with Server and Client each other .

VB.NET MultiThreaded Client Socket Programming


The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program MultiThreaded Client Socket Program is a windows based application . Here the client program is connected to Server's PORT 8888 , and IP Address here we give Server Address as " 127.0.0.1 " , because Server and Client program run on the same machine.

clientSocket.Connect("127.0.0.1", 8888) When the Client get conncted to the Server , the Server make a separate thread for Client's communication . So we can connect more than one client and communicate at the same time. Create a new VB.NET Windows based application and put the following source code in the Project. Download Source Code Print Source Code

Imports System.Net.Sockets Imports System.Text Public Class Form1 Dim clientSocket As New System.Net.Sockets.TcpClient() Dim serverStream As NetworkStream Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim serverStream As NetworkStream = clientSocket.GetStream() Dim buffSize As Integer Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes("Message from Client$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim inStream(10024) As Byte buffSize = clientSocket.ReceiveBufferSize serverStream.Read(inStream, 0, buffSize) Dim returndata As String = _ System.Text.Encoding.ASCII.GetString(inStream) msg("Data from Server : " + returndata) End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load msg("Client Started") clientSocket.Connect("127.0.0.1", 8888) Label1.Text = "Client Socket Program - Server Connected ..." End Sub Sub msg(ByVal mesg As String)

TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg End Sub End Class

The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program You have to run Server program first and then Client program , then only you can communicate with Server and Client each other .

VB.NET Chat Server Program


Multithreaded Socket Programming is the basic idea behind a TCP Chat Server communication. In the previous section Multithreaded Socket Programming we can see a Multithreaded Server Socket Program communicate with more than one Client at the same time . But there the communication is happening only between Server to Client or Client to Server , there is no communication between Client to Client . In a Multithreaded Chat Server , a Client can communicate with any number of Clients , currently connected on the Chat Server .

Each Clients send messages to Server and the Server broadcast the message to all Clients currently connected to the Chat Server . From the following diagram you can see how a VB.NET TCP Chat Server is handling communication between Client to Client .

The VB.NET Multithreaded Chat Server program has two sections. 1. Chat Server 2. Chat Client Download Chat Server Program . Chat Server Download Chat Client Download

How to run Chat Server program ? After create the Chat Server and Chat Client , run the Server program first and then run the Client program . In the Client program Enter a Chat name and click the " Connect to Server " button . Then you can see the message in the Server program User Joined Chat Room . Similarly you can connect more than one Clients at the same time and start chatting each other. It is better to Compile and Build the program and run from the .exe files .

VB.NET Chat Server


The basic function of the Chat Server here is to listening for the connection request from Clients and when the Server get a message , it Broadcast the message to all Clients currently connected to the Server .

The VB.NET Multithreaded Chat Server Program has two sections. 1. Chat Server 2. Chat Client

The Chat Server here is a VB.NET Console based application and is listening to the PORT 8888 for the connection request from clients . When the server gets a connection request , it add the name of the Client into a clientsList ( Here it is a Hashtable ) and create a new thread for communication with Server . When the Server get a message from any client , it select all the Clients from clientsList and send the message to all Clients ( ie we can say Broadcast ) in the clientsList . So each Client can see the message each other and they can communicate through Chat Server. The client list we implemented here in a HashTable . The clientsList stores the Client Name ( ie the first message from Client ) and an instance of the Client Socket . When a Chat Client connected to Server , the Server create a new Thread for communication . Here we implement a Class handleClient for handling Client as a separate Thread . The Class handleClient has a function doChat() is handling the communication between the Server side Client Socket and the incoming Client Socket. When Server get a message from any of the currently connected Chat Client , the Server Broadcast the message to all Clients. Here we implement a function broadcast for sending messages to all Clients . Create a new VB.NET Console based application and put the following source code into the Project. Download Source Code
Imports System.Net.Sockets Imports System.Text Module Module1 Dim clientsList As New Hashtable Sub Main() Dim serverSocket As New TcpListener(8888) Dim clientSocket As TcpClient Dim counter As Integer serverSocket.Start() msg("Chat Server Started ....") counter = 0 While (True) counter += 1 clientSocket = serverSocket.AcceptTcpClient()

Print Source Code

Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _ dataFromClient.Substring(0, dataFromClient.IndexOf("$")) clientsList(dataFromClient) = clientSocket broadcast(dataFromClient + " Joined ", dataFromClient, False) msg(dataFromClient + " Joined chat room ") Dim client As New handleClinet client.startClient(clientSocket, dataFromClient, clientsList) End While clientSocket.Close() serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub Private Sub broadcast(ByVal msg As String, _ ByVal uName As String, ByVal flag As Boolean) Dim Item As DictionaryEntry For Each Item In clientsList Dim broadcastSocket As TcpClient broadcastSocket = CType(Item.Value, TcpClient) Dim broadcastStream As NetworkStream = _ broadcastSocket.GetStream() Dim broadcastBytes As [Byte]() If flag = True Then broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)

Else broadcastBytes = Encoding.ASCII.GetBytes(msg) End If broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length) broadcastStream.Flush() Next End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Dim clientsList As Hashtable Public Sub startClient(ByVal inClientSocket As TcpClient, _ ByVal clineNo As String, ByVal cList As Hashtable) Me.clientSocket = inClientSocket Me.clNo = clineNo Me.clientsList = cList Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat) ctThread.Start() End Sub Private Sub doChat() 'Dim infiniteCounter As Integer Dim requestCount As Integer Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim sendBytes As [Byte]() Dim serverResponse As String Dim rCount As String requestCount = 0 While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _

dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("From client - " + clNo + " : " + dataFromClient) rCount = Convert.ToString(requestCount) broadcast(dataFromClient, clNo, True) Catch ex As Exception MsgBox(ex.ToString) End Try End While End Sub End Class End Module

Download Chat Server Program . Chat Server Download Chat Client Download Refer to Chat Server Program for how to run this program .

VB.NET Chat Client


The Chat Client is a Windows based Application and its main function is to send message to Chat Server.

The VB.NET Multithreaded Chat Server Program has two sections. 1. Chat Server 2. Chat Client The Chat Client here is to connect the PORT 8888 of the Chat Server in " 127.0.0.1 " . Here we give " 127.0.0.1 " , because Chat Server and Chat Client are running on the same machine . When we start the Chat Client program , we have to enter a User Name for identifying in Server . The Client program connect to the Chat Server and start a Thread for receive the messages from client, . Here we implement an infinite loop in the function getMessage() and call this function in a Thread . Create a new VB.NET Windows based project and put the source code in it. Download Source Code
Imports System.Net.Sockets Imports System.Text Public Class Form1

Print Source Code

Dim Dim Dim Dim

clientSocket As New System.Net.Sockets.TcpClient() serverStream As NetworkStream readData As String infiniteCounter As Integer

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes(TextBox2.Text + "$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() End Sub Private Sub msg() If Me.InvokeRequired Then Me.Invoke(New MethodInvoker(AddressOf msg)) Else TextBox1.Text = TextBox1.Text + _ Environment.NewLine + " >> " + readData End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click readData = "Conected to Chat Server ..." msg() clientSocket.Connect("127.0.0.1", 8888) 'Label1.Text = "Client Socket Program - Server Connected ..." serverStream = clientSocket.GetStream() Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes(TextBox3.Text + "$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim ctThread As Threading.Thread = _ New Threading.Thread(AddressOf getMessage) ctThread.Start() End Sub Private Sub getMessage()

For infiniteCounter = 1 To 2 infiniteCounter = 1 serverStream = clientSocket.GetStream() Dim buffSize As Integer Dim inStream(10024) As Byte buffSize = clientSocket.ReceiveBufferSize serverStream.Read(inStream, 0, buffSize) Dim returndata As String = _ System.Text.Encoding.ASCII.GetString(inStream) readData = "" + returndata msg() Next End Sub End Class

Download Chat Server Program . Chat Server Download Chat Client Download Refer to Chat Server Program for how to run this program .

Checking Internet Connection


The Microsoft WinINet API enables applications to access standard Internet protocols, such as FTP and HTTP. Many of you want to know if a computer has an active Internet connection before trying to connect to the internet using some communication interface. We can determine it by using one of WinINet function for check the status of internet connection in a computer.
Private Declare Function InternetGetConnectedState Lib "wininet" _ (ByRef conn As Long, ByVal val As Long) As Boolean

InternetGetConnectedState function retrieves the connected state of the local system. A return value of TRUE from InternetGetConnectedState indicates that at least one connection to the Internet is available. Download Source Code
Imports System.Runtime.InteropServices Public Class Form1 Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef conn As Long, ByVal val As Long) As Boolean Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Out As Integer If InternetGetConnectedState(Out, 0) = True Then MsgBox("Connected !") Else MsgBox("Not Connected !") End If End Sub End Class

Print Source Code

How to validate email address


An Email address has two parts. The part before the @ sign is the local part of the address, and the part after the @ sign is a domain name to which the email message will be sent .
feedback@net-informations.com

Trying to match these restrictions is a complex task, often resulting in long regular expressions. The .NET Framework provides an extensive set of regular expression tools that enable you to efficiently create, compare, and modify strings as well as rapidly parse large amounts of text and data to search for, remove, and replace text patterns.

Regex.IsMatch("feedback@net-informations.com", pattern)

Regex.IsMatch Method (String, String) Indicates whether the specified regular expression finds a match in the specified input string. The pattern parameter consists of various regular expression language elements that symbolically describe the string to match pattern . The following vb.net source code shows how to validate an email address with the help of regular expressions. Download Source Code
Imports System.Text.RegularExpressions Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim pattern As String pattern = "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zAZ]{2,9})$" If Regex.IsMatch("feedback@net-informations.com", pattern) Then MsgBox("Valid Email address ") Else MsgBox("Not a valid Email address ") End If End Sub End Class

Print Source Code

VB.NET FILE TUTORIALS


VB.NET Files
VB.NET implements its File and Directory operations in the namespace System.IO . The classes in the namespace System.IO provides various methods to retrieve and changes information about Directories and Files . The following tutorials provides various operations in Directories as well as Files using System.IO namespace.

How to VB.NET Directory operations

Using Directory class , we can create , delete , move etc. operations in VB.NET. Because of the static nature of Directory class , we do not have to instantiate the class. We can call the methods in the class directly from the Directory class. How to create a directory ? In order to create a new directory , we can call CreateDirectory directly from Directory class. Syntax : Directory.CreateDirectory(DirPath) DirPath : The name of the new directory VB.NET : Directory.CreateDirectory("c:\testdir") How to check a directory exist or not ? Before we creating a directory , we usually check that directory exist or not. For that we are using the Exists method in the Directory class. Syntax : Directory.Exists(DirPath) as Boolean DirPath : The name of the directory Boolean : Returns true or false , if directory exist it Returns true , else it Returns false VB.NET : Directory.Exists("c:\testdir") How to move a Directory ? If we want to move a directory and its contents from one location to another , we can use the Move method in the Directory class. Syntax : Move(sourceDirName,destDirName) sourceDirName : The source directory we want to move.

destDirName : The destinations directory name. VB.NET : Directory.Move("c:\testdir1\testdir2", "c:\testdir") How to delete a Directory ? When we want to delete a directory we can use the Delete method in the Directory class Syntax : Delete(DirPath) DirPath : The Directory we want to delete. VB.NET : Directory.Delete("c:\testdir1") The following VB.NET source code shows these operations : Download Source Code Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click If Directory.Exists("c:\testDir1") Then 'shows message if testdir1 exist MsgBox("Directory 'testDir' Exist ") Else 'create the directory testDir1 Directory.CreateDirectory("c:\testDir1") MsgBox("testDir1 created ! ") 'create the directory testDir2 Directory.CreateDirectory("c:\testDir1\testDir2") MsgBox("testDir2 created ! ") 'move the directory testDir2 as testDir in c: "c:\testDir") MsgBox("testDir2 moved ") 'delete the directory testDir1 Directory.Delete("c:\testDir1") MsgBox("testDir1 deleted ")

Directory.Move("c:\testDir1\testDir2",

End If End Sub End Class

When you executing this program you can see , first it create directory testDir1 and then testDir2 is creating inside testDir1 , Next the program move the testDir2 to testDir . Finally it delete the directory testDir1. After the execution you can see testDir in c:\

How to VB.NET Files operations


File class is using for the File operations in VB.NET. We can create , delete , copy etc. operations do with File class. How to create a File ? In order to create a new File , we can call Create method in the File class. Syntax : File.Create(FilePath) FilePath : The name of the new File Object File.Create("c:\testFile.txt") How to check a File exist or not ? Before we creating a File object , we usually check that File exist or not. For that we are using the Exists method in the File class. Syntax : File.Exists(FilePath) as Boolean FilePath : The name of the File Boolean : Returns true or false , if File exist it Returns true else Returns false

VB.NET : File.Exists("c:\testFile.txt") The following VB.NET source code shows these operations :
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If File.Exists("c:\testFile.txt") Then 'shows message if testFile exist MsgBox("File 'testFile' Exist ") Else 'create the file testFile.txt File.Create("c:\testFile.txt") MsgBox("File 'testFile' created ") End If End Sub End Class

When you execute this source code , it first check the File exist or not , If exist it shows message file exist , else it create a new File Object . How to Copy a File ? If we want the Copy of the File Object we can use the Copy method in File class. Syntax : Copy(sourceFileName, destFileName) sourceFileName : The source file we want to move. destFileName : The destinations file name. VB.NET : File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt") How to delete a File Object ?

When we want to delete a File Object we can use the Delete methods in the File class Syntax : Delete(FilePath) DirPath : The File Object you want to delete. VB.NET : File.Delete("c:\testDir\testFile.txt") The following VB.NET source code shows these operations : Download Source Code Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If Not File.Exists("c:\testFile.txt") Then MsgBox("FIle not exist ") Else File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt") MsgBox("File Copied ") File.Delete("c:\testFile.txt") MsgBox("file deleted ") End If End Sub End Class

When you execute this program first it check whether the file exist or not , if it is not exist it shows message file does not exist, if it exist it copied the file to testDir director and it delete the file from the c:\.

How to VB.NET FileStream operations


The FileStream Class represents a File in the Computer. FileStream allows to move data to and from the stream as arrays of bytes. We operate File using FileMode in FileStream Class

Some of FileModes as Follows : FileMode.Append : Open and append to a file , if the file does not exist , it create a new file FileMode.Create : Create a new file , if the file exist it will append to it FileMode.CreateNew : Create a new File , if the file exist , it throws exception FileMode.Open : Open an existing file How to create a file using VB.NET FileStream ? The following example shows , how to write in a file using FileStream. Download Source Code Print Source Code

Imports System.IO Imports System.Text Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim wFile As System.IO.FileStream Dim byteData() As Byte byteData = Encoding.ASCII.GetBytes("FileStream Test1") wFile = New FileStream("streamtest.txt", FileMode.Append) wFile.Write(byteData, 0, byteData.Length) wFile.Close() Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class

When we execute the program , it create a new File and write the content to it .

How to VB.NET TextReader operations


Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. Download Source Code Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim line As String Dim readFile As System.IO.TextReader = New _ StreamReader("C:\TextReader.txt") While True line = readFile.ReadLine() If line Is Nothing Then Exit While Else MsgBox(line) End If End While readFile.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class

When you execute this program the TextReader read the file line by line.

How to VB.NET Simple TextReader

Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. The following program using TextReader , Read the entire content of the file into a String Download Source Code Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim line As String Dim readFile As System.IO.TextReader = New _ StreamReader("C:\Test1.txt") line = readFile.ReadToEnd() MsgBox(line) readFile.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class

When you execute this program , TextReader read the entire file in one stretch.

How to VB.NET TextWriter


Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. The following sample source showing how write in a file using TextWriter . Download Source Code
Imports System.IO Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim writeFile As System.IO.TextWriter = New _ StreamWriter("c:\textwriter.txt") writeFile.WriteLine("vb.net-informations.com") writeFile.Flush() writeFile.Close() writeFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class

When you execute this source code , you will get a file TextWriter.txt and inside it written vb.net-informations.com

How to VB.NET BinaryReader


BinaryReader Object works at lower level of Streams. BinaryReader is used for read premitive types as binary values in a specific encoding stream. Binaryreader Object works with Stream Objects that provide access to the underlying bytes. For creating a BinaryReader Object , you have to first create a FileStream Object and then pass BinaryReader to the constructor method . Dim readStream As FileStream readStream = New FileStream("c:\testBinary.dat", FileMode.Open) Dim readBinary As New BinaryReader(readStream) The main advantages of Binary information is that stores files as Binary format is the best practice of space utilization.

Download Source Code

Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim readStream As FileStream Dim msg As String Try readStream = New FileStream("c:\testBinary.dat", FileMode.Open) Dim readBinary As New BinaryReader(readStream) msg = readBinary.ReadString() MsgBox(msg) readStream.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

BinaryWriter you can use in the same way to write as binary.

How to VB.NET BinaryWriter


The BinaryWriter Object works at lower level of Streams. BinaryWriter is used for write premitive types as binary values in a specific encoding stream. BinaryWriter Object works with Stream Objects that provide access to the underlying bytes. For creating a BinaryWriter Object , you have to first create a FileStream Object and then pass BinaryWriter to the constructor method . Dim writeStream As FileStream writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream)

The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization. Download Source Code Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay.Write("This is a test for BinaryWriter !") writeBinay.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

BinaryReader you can use in the same way to read as binary.

How to VB.NET BinaryWriter


The BinaryWriter Object works at lower level of Streams. BinaryWriter is used for write premitive types as binary values in a specific encoding stream. BinaryWriter Object works with Stream Objects that provide access to the underlying bytes. For creating a BinaryWriter Object , you have to first create a FileStream Object and then pass BinaryWriter to the constructor method . Dim writeStream As FileStream writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream)

The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization. Download Source Code Print Source Code

Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay.Write("This is a test for BinaryWriter !") writeBinay.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

BinaryReader you can use in the same way to read as binary.

How to Copy , Delete File


The File Class is using the operations such as copying, moving, renaming, creating, opening, deleting, and appending to files.
File.Copy("c:\\temp.txt", "c:\\copytemp.txt", True) File.Delete("c:\\copytemp.txt")

IOException is the base class for exceptions thrown while accessing information using streams, files and directories. FileNotFoundException Class is thrown the exception when an attempt to access a file that does not exist on disk fails.
Try

'code here Catch ex As System.IO.FileNotFoundException 'exception here End Try

The following vb.net program shows how to use File Class for copying and deleting a text file and also its shows how to handle System.IO.FileNotFoundException Class. Download Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try File.Copy("c:\\temp.txt", "c:\\copytemp.txt", True) File.Delete("c:\\copytemp.txt") Catch ex As System.IO.FileNotFoundException MsgBox(ex.ToString()) End Try End Sub End Class

Print Source Code

VB.NET ADO.NET

VB.NET ADO.NET Tutorial


ADO.NET is a data access technology from Microsoft .Net Framework , which provides communication between relational and nonrelational systems through a common set of components . ADO.NET was built for a disconnected architecture , so it enables truly disconnected data access and data manipulation through its Dataset Object, which is completely independent from the Data Source.

The two key components of ADO.NET are Data Providers and DataSet . The .Net Framework includes mainly three Data Providers for ADO.NET. The Microsoft SQL Server , OLEDB and ODBC are the main Data Providers in the .Net Framework. In the following pages you can see each component of ADO.NET in details with source code.

ADO.NET Architecture
ADO.NET is a data access technology from Microsoft .Net Framework , which provides communication between relational and nonrelational systems through a common set of components . ADO.NET consist of a set of Objects that expose data access services to the .NET environment. ADO.NET is built for disconnected architecture , so it enables truly disconnected Data Access and Data Manipulation through its Dataset Object, which is completely independent from the Data Source.

The two key components of ADO.NET are Data Providers and DataSet . The .Net Framework includes mainly three Data Providers for ADO.NET. They are the Microsoft SQL Server Data Provider, OLEDB Data Provider and ODBC Data Provider. SQL Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses OdbcConnection Object respectively.

The four Objects from the .Net Framework provide the functionality of Data Providers in the ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object. The Connection Object provides physical connection to the Data Source. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data Source. The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. Finally the DataAdapter Object , which populate a Dataset Object with results from a Data Source .

DataSet provides a disconnected representation of result sets from the Data Source, and it is completely independent from the Data Source. DataSet provides much greater flexibility when dealing with related Result Sets. DataSet consists of a collection of DataTable

objects that you can relate to each other with DataRelation objects. The DataTable contains a collection of DataRow and DataCoulumn Object which contains Data. The DataAdapter Object provides a bridge between the DataSet and the Data Source.

In the following section you can see each of the ADO.NET components in details with vb.net source code.

Advantages of ADO.Net over ADO


ADO stands for ActiveX Data Objects and it relies on COM whereas ADO.NET relies on managed providers defined by the .NET CLR (Common Language Runtime). ADO.NET provides consistent access to data sources such as SQL Server, as well as data sources exposed through OLE DB and XML. While there are similarities between ADO and ADO.NET, the way they operate and their foundations are quite different. The following are some Advantages of ADO.Net over ADO in basic level.

A major difference in creating connections with ADO and ADO.NET is that ADO fits all connections to all types of data sources into a single Connection object. ADO.NET can have separate Objects that represent connections to different data sources. In ADO.NET you can create multiple data provider namespaces to connect specifically with a particular data source, making access faster and more efficient and allowing each namespace to exploit the features of its targeted data provider.
Dim connection As SqlConnection connection = New SqlConnection("connetionString") Dim connection As OleDbConnection connection = New OleDbConnection("connetionString")

ADO allows you to create client side cursors only whereas ADO.NET gives you the choice of either using client side or server side cursors. ADO.NET introduces a new way of getting a single value from a query's results when you expect only one row and one column to return. The ADO.NET command object has an ExecuteScalar method which returns the first row and column's value from its associated query. ADO.Net dataset represents in memory representation of a database. ADO recordsets is merely a set of rows retrieved from a data source. ADO recordsets can hold data from one data source at a time. ADO.Net datasets can hold data from various sources and integrate the data and write it back to one or several data sources. The ADO.NET Framework supports two models of Data Access Architecture, Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. In the case of Data Communication , ADO objects communicate in binary mode while ADO.NET uses XML for passing the data. You can find more information on ADO to ADO.NET from the following link : http://msdn.microsoft.com/en-us/magazine/cc163954.aspx

Connected and Disconnected Data Access Architecture


The ADO.NET Framework supports two models of Data Access Architecture, Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. In Connection Oriented Data Access Architecture the application makes a connection to the Data Source and then interact with it through SQL requests using the same connection. In these cases the application stays connected to the database system even when it is not using any Database Operations. ADO.Net solves this problem by introduces a new component called Dataset. The DataSet is the central component in the ADO.NET Disconnected Data Access Architecture. A DataSet is an in-memory data store that can hold multiple tables at the same time. DataSets only hold data and do not interact with a Data Source. One of the key characteristics of the DataSet is that it has no knowledge of the underlying Data Source that might have been used to populate it.
Dim ds As New DataSet

In Connection Oriented Data Access, when you read data from a database by using a DataReader object, an open connection must be maintained between your application and the Data Source. Unlike the DataReader, the DataSet is not connected directly to a Data Source through a Connection object when you populate it. It is the DataAdapter that manages connections between Data Source and Dataset by fill the data from Data Source to the Dataset and giving a disconnected behavior to the Dataset. The DataAdapter acts as a bridge between the Connected and Disconnected Objects.
Dim adapter As New SqlDataAdapter("sql", "connection") Dim ds As New DataSet adapter.Fill(ds, "Src Table")

By keeping connections open for only a minimum period of time, ADO .NET conserves system resources and provides maximum security for databases and also has less impact on system performance.

ADO.NET ConnectionString

Connection String is a normal String representation which contains Database connection information to establish the connection between Datbase and the Application. The Connection String includes parameters such as the name of the driver, Server name and Database name , as well as security information such as user name and password. Data providers use a connection string containing a collection of parameters to establish the connection with the database. The .NET Framework provides mainly three data providers: Microsoft SQL Server, OLEDB and ODBC. Here you can see how to make connection string to these ADO.NET Data Providers. Microsoft SQL Server Connection String connetionString ="Data Source = ServerName; Initial Catalog = Databasename; User ID = UserName; Password=Password" OLEDB Data Provider Connection String connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = yourdatabasename.mdb;" ODBC Connection String connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ = yourdatabasename.mdb;" Note : You have to provide the necessary informations to the Connection String attributes. In the following section you can see how to these ADO.NET Data Providers establish connection to the Databse in detail. SQL Server Connection OLEDB Connection ODBC Connection

ADO.NET Data Providers

The .Net Framework includes mainly three Data Providers for ADO.NET. They are the Microsoft SQL Server Data Provider , OLEDB Data Provider and ODBC Data provider. You can see from the following links how these Data Providers making connection to the specified data Sources. SQL Server Connection OLEDB Connection ODBC Connection

The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object. The following link shows in details about these Objects. Connection Command DataReader DataAdapter

How to handle null values


ADO.NET provides database connectivity between relational and non relational systems through a common set of components. The ADO.NET classes are divided into two components, the Data Providers and the DataSet. In many situations while reading data from Dataset, we have seen the error message like this,
Conversion from type 'DBNull' to type '' is not valid

Here is the solution for how to handle DBNull. The DBNull class represents a nonexistent value. The function IsDBNull returns True if the data type of expression evaluates to the DBNull type otherwise, IsDBNull returns False.
If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.Tables(0).Rows(i).Item(0))) End If

In the above code we are using the function IsDBNull to check wether the Dataset value is a DBNULL or not. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "your sql select statements here"

connection = New SqlConnection(connetionString) connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) connection.Close() Try If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.Tables(0).Rows(i).Item(0))) End If Catch ex As Exception MsgBox(ex.ToString()) End Try End Sub End Class

How to handle single quotes


The Microsoft .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return records. While we are inserting data into the database table we came across the messages like..
System.Data.SqlClient.SqlException: Incorrect syntax near ...

Incorrect syntax near '..'. Unclosed quotation mark after the character string ')'. We are getting the above error message because there is a problem while inserting single quoted character using in sql statements. For ex: We want to insert a string like "Microsoft's" , the system shows the above error messages, because we are trying to insert a single quoted character using in sql statement. We can solve this problem by replace any single quote with two quotes like "Microsoft''s" .

insert into tablename (field1) values('Microsoft''s')

For avoiding each time adding another single quote to the string , here we implement a function to replace the string with two single quotes.
Public Function convertQuotes(ByVal str As String) As String convertQuotes = str.Replace("'", "''") End Function

Download Source Code

Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String Dim field1 As String = "Microsoft's" Dim field2 As String = "VB.NET" connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "insert into tablename (field1,field2) values('" & convertQuotes(field1) & "','" & convertQuotes(field2) & "')" Try connection.Open() adapter.InsertCommand = New SqlCommand(sql, connection) adapter.InsertCommand.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub

'here is the function to handle single quoted characters Public Function convertQuotes(ByVal str As String) As String convertQuotes = str.Replace("'", "''") End Function End Class

ADO.NET DATA PROVIDERS HELP AND TUTORIALS

ADO.NET Data Providers help and Tutorial


The .Net Framework includes mainly three Data Providers for ADO.NET. The Microsoft SQL Server , OLEDB and ODBC are the main Data Providers included in the .Net Framework. You can see from the following links how these Data Providers making connection to the Data Sources . SQL Server Connection OLEDB Connection ODBC Connection

The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object. The Connection Object provides physical connection to the Data Source. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data Source. The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. Finally the DataAdapter Object , which populate a Dataset Object with results from a Data Source . The following link shows in details about these Objects. Connection Command DataReader DataAdapter
Royalty Free and Excel Compatible - SpreadsheetGear for .NET Featuring the fastest and most complete Excel compatible calculation engine - Download a free 30-day evaluation today! C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.

ADO.NET Connection Object


The Connection Object is a part of ADO.NET Data Provider and it is a unique session with the Data Source. In .Net Framework the Connection Object is Handling the part of physical communication between the application and the Data Source. Depends on the parameter specified in the Connection String , ADO.NET Connection Object connect to the specified Database and open a connection between the application and the Database . When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the Database. Once the Database activity is over , Connection should be closed and release the resources .

In ADO.NET the type of the Connection is depend on what Database system you are working with. The following are the commonly using the connections in the ADO.NET SqlConnection OleDbConnection OdbcConnection
C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details. Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details

ADO.NET SQL Server Connection

The SqlConnection Object is Handling the part of physical communication between the application and the SQL Server Database. An instance of the SqlConnection class in .NET Framework is supported the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the database resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the SQL Server Database.
Download Source Code Print Source Code

Take our 3-Minute Hosting Decisions Survey Working Effectively with Legacy Code Participants will be eligible to win a $100 Amazon gift certificate. Take Learn how to find and create seams in your application, no matter the short survey here. "Legacy" it may be, and over time improve application's design. Read more...
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

You have to provide the necessary informations to the Connection String. connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password"

From the above statement replace ServerName, DatabaseName, UserName, Password to the actual names.

ADO.NET Connection Object


The Connection Object is a part of ADO.NET Data Provider and it is a unique session with the Data Source. In .Net Framework the Connection Object is Handling the part of physical communication between the application and the Data Source. Depends on the parameter specified in the Connection String , ADO.NET Connection Object connect to the specified Database and open a connection between the application and the Database . When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the Database. Once the Database activity is over , Connection should be closed and release the resources .

In ADO.NET the type of the Connection is depend on what Database system you are working with. The following are the commonly using the connections in the ADO.NET SqlConnection OleDbConnection OdbcConnection

Working Effectively with Legacy Code Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...

Working Effectively with Legacy Code Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...

ADO.NET SQL Server Connection


The SqlConnection Object is Handling the part of physical communication between the application and the SQL Server Database. An instance of the SqlConnection class in .NET Framework is supported the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the database resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the SQL Server Database. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString)

Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

You have to provide the necessary informations to the Connection String. connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" From the above statement replace ServerName, DatabaseName, UserName, Password to the actual names.

ADO.NET OLEDB Connection


An instance of the OleDbConnection class in .NET Framework is supported the OLEDB Data Provider. The OleDbConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the Database connected by the OLEDB Data Provider. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;" cnn = New OleDbConnection(connetionString)

Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

You have to provide the necessary informations to the Connection String. connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = yourdatabasename.mdb;" From the above statement replace yourdatabasename.mdb to the actual names.

ADO.NET ODBC Connection


An instance of the OdbcConnection class in .NET Framework is supported the ODBC Data Provider. The OdbcConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the Database connected by the ODBC Data Provider. Download Source Code Print Source Code

Imports System.Data.Odbc Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim connetionString As String Dim cnn As OdbcConnection connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;" cnn = New OdbcConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

You have to provide the necessary informations to the Connection String. connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ = yourdatabasename.mdb;" From the above statement replace yourdatabasename.mdb to the actual names.

ADO.NET Connection Object


The Connection Object is a part of ADO.NET Data Provider and it is a unique session with the Data Source. In .Net Framework the Connection Object is Handling the part of physical communication between the application and the Data Source. Depends on the parameter specified in the Connection String , ADO.NET Connection Object connect to the specified Database and open a connection between the application and the Database . When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the Database. Once the Database activity is over , Connection should be closed and release the resources .

In ADO.NET the type of the Connection is depend on what Database system you are working with. The following are the commonly using the connections in the ADO.NET SqlConnection OleDbConnection OdbcConnection

ADO.NET Command
The Command Object in ADO.NET executes SQL statements and Stored Procedures against the data source specified in the Connection Object. The Command Object required an instance of a Connection Object for executing the SQL statements. That is, for retrieving data or execute an SQL statement against a Data Source , you have to create a Connection Object and open a connection to the Data Source, and assign the open connection to the connection property of the Command Object. When the Command Object return result set , a Data Reader is used to retrieve the result set.

The Command Object has a property called CommandText, which contains a String value that represents the command that will be executed in the Data Source. When the CommandType property is set to StoredProcedure, the CommandText property should be set to the name of the stored procedure. Click the following links to see some important built in methods uses in the Command Object to execute the SQL statements. ExecuteNonQuery ExecuteReader ExecuteScalar

ADO.NET ExecuteNonQuery in SqlCommand Object


ExecuteNonQuery() is one of the most frequently used method in SqlCommand Object and is used for executing statements that do not return result set. ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update and Delete perform by ExecuteNonQuery().

The following example shows how to use the method ExecuteNonQuery() through SqlCommand Object. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(Sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close() MsgBox(" ExecuteNonQuery in SqlCommand executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here" You have to replace the string with your realtime variables.

ADO.NET ExecuteNonQuery in OleDbCommand Object

ExecuteNonQuery() is one of the most frequently used method in OleDbCommand Object and is used for executing statements that do not return result set. ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update and Delete perform by ExecuteNonQuery(). The following example shows how to use the method ExecuteNonQuery() through OleDbCommand Object. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close() MsgBox(" ExecuteNonQuery in OleDbConnection executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here"

You have to replace the string with your realtime variables.

ADO.NET ExecuteScalar in SqlCommand Object


ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set. If the Result Set contains more than one columns or rows , it takes only the first column of first row, all other values will ignore. If the Result Set is empty it will return a Null reference. It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose() cnn.Close() MsgBox(" No. of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ")

End Try End Sub End Class

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables.

ADO.NET ExecuteScalar in OleDbCommand Object


ExecuteScalar() in OleDbCommand Object is used for get a single value from Database after its execution. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set. If the Result Set contains more than one columns or rows , it takes only the first column of first row, all other values will ignore. If the Result Set is empty it will return a Null reference. It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose()

cnn.Close() MsgBox(" No of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables.

ADO.NET ExecuteReader in SqlCommand Object


ExecuteReader() in SqlCommand Object send the SQL statements to Connection Object and populate a SqlDataReader Object based on the SQL statement. When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The SqlDataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String Dim reader As SqlDataReader connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

sql = "Your SQL Statement Here ,

like Select * from product"

cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " End While reader.Close() cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

" & reader.Item(2))

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here , like Select * from product" You have to replace the string with your realtime variables.

ADO.NET ExecuteReader in OleDbCommand Object


ExecuteReader() in OleDbCommand Object send the SQL statements to Connection Object and populate a OleDbDataReader Object based on the SQL statement. When the ExecuteReader method in OleDbCommand Object execute , it instantiate a OleDb.OleDbDataReader Object. The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The OleDbDataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object. Download Source Code
Imports System.Data.OleDb

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String Dim reader As OleDbDataReader connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " End While reader.Close() cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

" & reader.Item(2))

connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.

How to ADO.NET DataReader

DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The DataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object.

DataReader = Command.ExecuteReader() DataReader Object provides a connection oriented data access to the data Sources. A Connection Object can contain only one DataReader at a time and the connection in the DataReader remains open and cannot be used for any other purpose while data is being accessed. When started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . DataReader.Raed() There are two types of DataReader in ADO.NET. They are SqlDataReader and the OleDbDataReader. The System.Data.SqlClient and System.Data.OleDb are containing these DataReaders respectively. From the following link you can see in details about these classes. SqlDataReader OleDbDataReader

How to ADO.NET SqlDataReader


SqlDataReader Object provides a connection oriented data access to the SQL Server data Sources. ExecuteReader() in the SqlCommand Object send the SQL statements to SqlConnection Object and populate a SqlDataReader Object based on the SQL statement. Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. When started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . SqlDataReader.Read() Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " End While

" & sqlReader.Item(2))

sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" You have to replace the string with your realtime variables.

How to ADO.NET OleDbDataReader


OleDbDataReader Object provides a connection oriented data access to the OLEDB Data Sources. ExecuteReader() in the OleDbCommand Object send the SQL statements to OleDbConnection Object and populate an OleDbDataReader Object based on the SQL statement. Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() When the ExecuteReader method in OleDbCommand Object execute , it instantiate an OleDb.OleDbDataReader Object. When started to read from an OleDbDataReader it should always be open and positioned prior to the first record. The Read() method in the OleDbDataReader is used to read the rows from OleDbDataReader and it always moves forward to a new valid row, if any row exist . OleDbDataReader.Read() Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim Dim Dim Dim

connetionString As String oledbCnn As OleDbConnection oledbCmd As OleDbCommand sql As String

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbCmd = New OleDbCommand(sql, oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() While oledbReader.Read MsgBox(oledbReader.Item(0) & " - " & oledbReader.Item(1) & " End While oledbReader.Close() oledbCmd.Dispose() oledbCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

" & oledbReader.Item(2))

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.

How to Multiple Result Sets in ADO.NET


The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()

In some situations we need to pass multiple SQL statements to the Command Object. In this situations the SqlDataReader returns multiple ResultSets also. For retrieveing multiple ResultSets from SqlDataReader we use the NextResult() method of the SqlDataReader. SqlDataReader.NextResult() In the following source code demonstrating how to get multiple result sets from SqlDataReader() . Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox("From first SQL - " & sqlReader.Item(0) & " End While sqlReader.NextResult() While sqlReader.Read() MsgBox("From second SQL End While " & sqlReader.Item(0) & " " & sqlReader.Item(1))

" & sqlReader.Item(1))

sqlReader.NextResult() While sqlReader.Read() MsgBox("From third SQL End While " & sqlReader.Item(0) & " " & sqlReader.Item(1))

sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails" You have to replace the string with your realtime variables.

Schema Informations from SqlDataReader


The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. DDim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While a SqlDataReader is open, you can retrieve schema information about the current result set using the GetSchemaTable method. GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result set. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim Dim Dim Dim

connetionString As String sqlCnn As SqlConnection sqlCmd As SqlCommand sql As String

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() Dim schemaTable As DataTable = sqlReader.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.Rows For Each column In schemaTable.Columns MsgBox(String.Format("{0} = {1}", column.ColumnName, row(column))) Next Next sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" You have to replace the string with your realtime variables.

Schema Informations from OleDbDataReader

The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. When the ExecuteReader method in oledbCmd Object execute , it instantiate a OleDb.OleDbDataReader Object. Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() While a OleDbDataReader is open, you can retrieve schema information about the current result set using the GetSchemaTable method. GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result set. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbCmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbCmd = New OleDbCommand(sql, oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() Dim schemaTable As DataTable = oledbReader.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.Rows For Each column In schemaTable.Columns MsgBox(String.Format("{0} = {1}", column.ColumnName, row(column))) Next Next oledbReader.Close() oledbCmd.Dispose() oledbCnn.Close()

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.

What is DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication between the Dataset and the Datasource. We can use the DataAdapter in combination with the DataSet Object. That is these two objects combine to enable both data access and data manipulation capabilities.

The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source. The Insert , Update and Delete SQL operations , we are using the continuation of the Select command perform by the DataAdapter. That is the DataAdapter uses the Select statements to fill a DataSet and use the other three SQL commands (Insert, Update, delete) to transmit changes back to the Database. From the following links describe how to use SqlDataAdapter and OleDbDataAdapter in detail. SqlDataAdapter

OleDbDataAdapter

What is SqlDataAdapter
SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset Object. Dim adapter As New SqlDataAdapter The SqlDataAdapter Object and DataSet objects are combine to perform both data access and data manipulation operations in the SQL Server Database. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the SqlDataAdapter. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserNamePassword=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) adapter.SelectCommand = sqlCmd adapter.Fill(ds)

For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next adapter.Dispose() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

--

" & ds.Tables(0).Rows(i).Item(1))

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" You have to replace the string with your realtime variables.

What is OleDbDataAdapter
OleDbDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.OleDb namespace. OleDbDataAdapter provides the communication between the Dataset and the OleDb Data Sources. We can use OleDbDataAdapter Object in combination with Dataset Object. The OleDbDataAdapter Object and DataSet objects are combine to perform both Data Access and Data Manipulation operations in the OleDb Data Sources. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the OleDbDataAdapter. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet

Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbAdapter = New OleDbDataAdapter(sql, oledbCnn) oledbAdapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " & Next oledbAdapter.Dispose() oledbCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

ds.Tables(0).Rows(i).Item(1))

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.

Vb.NET ExecuteReader and ExecuteNonQuery


ExecuteReader : ExecuteReader used for getting the query results as a DataReader object. It is readonly forward only retrieval of records and it uses select command to read through the table from the first to the last.
Dim reader As SqlDataReader reader = Command.ExecuteReader() While reader.Read() MsgBox(reader.Item(0)) End While

reader.Close()

ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
Dim retValue As Integer Command = New SqlCommand(Sql, Connection) retValue = Command.ExecuteNonQuery()

Stored Procedures in VB.NET


The data provider is a set of components that include the Connection, Command, DataReader, and DataAdapter Objects. The command Object provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions. A stored procedure is a precompiled executable object that contains one or more SQL statements. A sample Stored Procedure is given below :
CREATE PROCEDURE SPPUBLISHER AS SELECT PUB_NAME FROM publishers GO

The above code create a procedure named as 'SPPUBLISHER' and it execute SQL statement that select all publisher name from publishers table from the PUB database. Using stored procedures, database operations can be encapsulated in a single command, optimized for best performance, and enhanced with additional security. To call a stored procedure from VB.NET application, set the CommandType of the Command object to StoredProcedure.
command.CommandType = CommandType.StoredProcedure

From the following source code you can see how to call a stored procedure from VB.NET application. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1.Click Dim Dim Dim Dim Dim Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connetionString As String connection As SqlConnection adapter As SqlDataAdapter command As New SqlCommand ds As New DataSet

Print Source Code

Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPPUBLISHER" adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class

Stored Procedure with Parameter

The ADO.NET classes are divided into two components, Data Providers and DataSet. A .NET data provider is used to connect to a database, execute commands, and retrieve results. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions. A Stored Procedure contain programming statements that perform operations in the database, including calling other procedures. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY @COUNTRY VARCHAR(20) AS SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY GO

The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String command.Parameters.Add(param)

The above code passing country parameter to the stored procedure from vb.net. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection

Print Source Code

Dim Dim Dim Dim

adapter As SqlDataAdapter command As New SqlCommand param As SqlParameter ds As New DataSet

Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPCOUNTRY" param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String command.Parameters.Add(param) adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class

VB.NET DATAADAPTER AND DATASET

How to ADO.NET DataAdapter with Dataset

DataAdapter is a part of the ADO.NET Data Provider. Dataset represents a collection of data retrieved from the Data Source and saving data to the Data Source. We can use Dataset in combination with DataAdapter class. These two objects combine to enable both data access and data manipulation capabilities. Functionally DataAdapter is the complex Object when compare to other Objects in the Data Provider .

Dataadapter with dataset - sql sever


SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from. So the SqlDataAdapter manage the communication between these two Objects. The SqlDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill method of the SqlDataAdapter for populating data in a Dataset. The following source code shows a simple program that uses SqlDataAdapter to retrieve data from Data Source with the help of SqlConnection object and populate the data in a Dataset.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter = New SqlDataAdapter("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1))

Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with dataset - OLEDB Data Source


OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object . The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects. The OleDbDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill method of the OleDbDataAdapter for populating data in a Dataset. The following source code shows a simple program that uses OleDbDataAdapter to retrieve data from Data Source with the help of OleDbConnection object and populate the data in a Dataset.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter("Your SQL Statement Here") oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next

Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter SelectCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism. The SelectCommand property of the SqlDataAdapter is a Command object that retrieves data from the data source. The following program shows the SqlDataAdapter using its SelectCommand property to retrieve the data from the Data Source.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter.SelectCommand = New SqlCommand("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox(ex.ToString)

End Try End Sub End Class

Dataadapter SelectCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object. The OleDbDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism. The SelectCommand property of the OleDbDataAdapter is a Command object that retrieves data from the data source. The following program shows the OleDbDataAdapter using its SelectCommand property to retrieve the data from the Data Source.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter.SelectCommand = New OleDbCommand("Your SQL Statement Here", connection) oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub

End Class

Dataadapter InsertCommand - Sql Server


SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The InsertCommand in SqlDataAdapter Object manages to insert the data in the specified Data Source . In the following Source Code shows how to insert data in the Data Source using SqlDataAdapter and SqlCommand object. Open a connection to the Data Source with the help of SqlConnection object and create a SqlCommand object with insert SQL statement, and assign the SqlCommand to the SqlDataAdapter's InsertCommand.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "insert into product (Product_id,Product_name,Product_price) values(7,'Product7',700)" Try connection.Open() adapter.InsertCommand = New SqlCommand(sql, connection) adapter.InsertCommand.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter InsertCommand - OLEDB Data Source

OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object . The InsertCommand in OleDbDataAdapter Object manages to insert the data in the specified Data Source . In the following Source Code shows how to insert data in the Data Source using OleDbDataAdapter and OleDbCommand object. Open a connection to the Data Source with the help of OleDbConnection object and create an OleDbCommand object with insert SQL statement, and assign the OleDbCommand to the SqlDataAdapter's InsertCommand.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "insert into user values('user1','password1')" Try connection.Open() oledbAdapter.InsertCommand = New OleDbCommand(sql, connection) oledbAdapter.InsertCommand.ExecuteNonQuery() MsgBox("Row(s) Inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter UpdateCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications, that are run on a DataSet object. The following code samples that demonstrate how to use the SqlDataAdapter object to update a SQL Server database using UpdateCommand properties in SqlDataAdapter.

Download Source Code

Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "update product set product_price = 1001 where Product_name ='Product7'" Try connection.Open() adapter.UpdateCommand = connection.CreateCommand adapter.UpdateCommand.CommandText = sql adapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter UpdateCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the Data Source with the data modifications that are run on a DataSet object. The following code samples that demonstrate how to use the OleDbDataAdapter object to update an OLEDB Data Source using UpdateCommand properties in OleDbDataAdapter.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "update Users set Password = 'new password' where UserID = 'user1'" Try connection.Open() oledbAdapter.UpdateCommand = connection.CreateCommand oledbAdapter.UpdateCommand.CommandText = sql oledbAdapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row(s) Updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter DeleteCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications, that are run on a DataSet object. The following code samples that demonstrate how to use the SqlDataAdapter object to update a SQL Server database using UpdateCommand properties in SqlDataAdapter.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString)

sql = "delete product where Product_name ='Product7'" Try connection.Open() adapter.DeleteCommand = connection.CreateCommand adapter.DeleteCommand.CommandText = sql adapter.DeleteCommand.ExecuteNonQuery() MsgBox("Row(s) deleted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter DeleteCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. The OleDbDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism. The InsertCommand, UpdateCommand, and DeleteCommand properties of the OleDbDataAdapter are Command objects that manage updates to the specified data source according to modifications. The following Source Code shows how to perform delete data from a database using DeleteCommand property of OleDbDataAdapter.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "delete from Users where UserID = 'user1'" Try connection.Open() oledbAdapter.DeleteCommand = connection.CreateCommand oledbAdapter.DeleteCommand.CommandText = sql oledbAdapter.DeleteCommand.ExecuteNonQuery() MsgBox("Row(s) Deleted !! ")

Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with CommandBuilder - Sql Server


The DataAdapter is a part of the ADO.NET Data Provider. ADO.NET DataAdapter is used to manage four separate Command objects. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object. The SqlCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the SqlCommandBuilder object. The SqlCommandBuilder opens the Connection associated with the DataAdapter and makes a round trip to the server each and every time it's asked to construct the action queries. It closes the Connection when it's done. The following Source Code demonstrate how to use the SqlDataAdapter object to update a SQL Server database with data modifications that are run on a DataSet object that is populated with data from a table in the database using SqlCommandBuilder object.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim cmdBuilder As SqlCommandBuilder Dim ds As New DataSet Dim sql As String Dim i As Int32 connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(sql, connection) cmdBuilder = New SqlCommandBuilder(adapter)

adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 ds.Tables(0).Rows(i).Item(2) = ds.Tables(0).Rows(i).Item(2) + 100 Next adapter.Update(ds.Tables(0)) connection.Close() MsgBox("Data updated ! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with CommandBuilder - OLEDB


The OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter is used to manage four separate Command objects. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object. The OleDbCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the OleDbCommandBuilder object. The OleDbCommandBuilder opens the Connection associated with the OleDbDataAdapter and makes a round trip to the server each and every time it's asked to construct the action queries. It closes the Connection when it's done. The following Source Code demonstrate how to use the OleDbDataAdapter object to update a OLEDB Data Source with data modifications that are run on a DataSet object that is populated with data from a table in the database using OleDbCommandBuilder object.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim oledbCmdBuilder As OleDbCommandBuilder Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"

connection = New OleDbConnection(connetionString) sql = "select * from tblUsers" Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) oledbAdapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 ds.Tables(0).Rows(i).Item(2) = "neweamil@email.com" Next oledbAdapter.Update(ds.Tables(0)) connection.Close() MsgBox("Email address updates !") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with DataGridView - Sql Server


SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Sourcewhere the data coming from. So the SqlDataAdapter manage the communication between these two Objects. The TableMapping Collections help the SqlDataAdapter to do this task. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object. The following source code demonstrate how to update a Dataset through SqlDataAdapter using a DataGridView. For running this source code , open a new VB.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code.
Download Source Code
Imports System.Data.SqlClient Public Class Form1 Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim cmdBuilder As SqlCommandBuilder

Print Source Code

Dim Dim Dim Dim

ds As New DataSet changes As DataSet sql As String i As Int32

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(Sql, connection) adapter.Fill(ds) connection.Close() DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try cmdBuilder = New SqlCommandBuilder(adapter) changes = ds.GetChanges() If changes IsNot Nothing Then adapter.Update(changes) End If MsgBox("Changes Done") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with DataGridView - OLEDB

OleDbDataAdapter provides the communication between the Dataset and the OLEDB Data Source with the help of OleDbConnection Object . The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects. The TableMapping Collection help the OleDbDataAdapter to do this task. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object. The following source code demonstrate how to update a Dataset through OleDbDataAdapter using a DataGridView. For running this source code , open a new VB.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code.
Download Source Code
Imports System.Data.OleDb Public Class Form1 Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim oledbCmdBuilder As OleDbCommandBuilder Dim ds As New DataSet Dim changes As DataSet Dim i As Integer Dim sql As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Sql = "select * from tblUsers" Try connection.Open() oledbAdapter = New OleDbDataAdapter(Sql, connection) oledbAdapter.Fill(ds) DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

Print Source Code

Button2.Click Try oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) changes = ds.GetChanges() If changes IsNot Nothing Then oledbAdapter.Update(ds.Tables(0)) End If ds.AcceptChanges() MsgBox("Save changes") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

VB.NET DataAdapter.Fill
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet.
DataAdapter.Fill(DataSet) DataAdapter.Fill(DataTable)

The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. If the data adapter encounters duplicate columns while populating a DataTable, it generates names for the subsequent columns, using the pattern "columnname1", "columnname2", "columnname3", and so on. From the following program you can understand how to use DataAdapter.Fill method in VB.NET applications. Download Source Code
Imports System.IO Imports System.Data.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Dim sqlAdp As SqlDataAdapter Dim ds As New DataSet Dim dt As New DataSet

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=userid; Password=password" cnn = New SqlConnection(connectionString) cnn.Open() sqlAdp = New SqlDataAdapter("select * from users", cnn) cnn.Close() 'connection close here , that is disconnected from data source sqlAdp.Fill(ds) sqlAdp.Fill(dt) 'fetching data from dataset in disconnected mode For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next 'fetching data from datatable in disconnected mode For i = 0 To dt.Tables(0).Rows.Count - 1 MsgBox(dt.Tables(0).Rows(i).Item(0)) Next End Sub End Class

Display Selected range of records


The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. When an instance of DataAdapter is created, the read or write properties are set to initial values. A DataSet is made up of a collection of tables, relationships, and constraints. In ADO.NET, DataTable objects are used to represent the tables in a DataSet. The DataSet is designed to be used in a disconnected mode.
Dim ds As New DataSet

In some situations we need to retrieve data only specific range of rows. In this situations we can fill the Dataset from DataAdapter only that specific range of rows. The following piece of code shows how to fill specific range of rows from DataAdapter to Dataset.

DataAdapter.Fill(Dataset, 5, 3, "tablename")

The above code will fill the Dataset starting from 5th row and no of rows 3. 5 is the starting row no 3 is no of rows we want to fill. Download Source Code
imports System.IO Imports System.Data.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Dim sqlAdp As SqlDataAdapter Dim ds As New DataSet Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=userid; Password=password" cnn = New SqlConnection(connectionString) cnn.Open() sqlAdp = New SqlDataAdapter("select * from users", cnn) cnn.Close() sqlAdp.Fill(ds, 5, 3, "users") '5 is starting row no. '3 is no of rows to retrieve For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next End Sub End Class

Print Source Code

VB.NET ADO.NET DATAVIEW TUTORIALS

VB.NET ADO.NET DataView Tutorial


The DataView provides different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable. DataView can be used to sort, filter, and search the data in a DataTable , additionally we can add new rows and modify the content in a DataTable. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. In the following links you can see how to use DataView in different ways

How to create a DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search in a DataTable , additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured both design time and run time . Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing the DataTable. We can create DataView in two different ways. We can use the DataView constructor, or you can create a reference to the DefaultView property of the DataTable. The DataView constructor can be empty, or it can take either a DataTable as a single argument, or a DataTable along with filter criteria, sort criteria, and a row state filter.

dataView = dataSet.Tables(0).DefaultView The following source code shows how to create a DataView in VB.NET. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Create DataView") adapter.Dispose() command.Dispose() connection.Close() dv = ds.Tables(0).DefaultView DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to sort DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured at both design time and run time . Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing that DataTable. We can sort single or multiple fields in a DataView , also we can specify the sort order like ASC (ascending) and DESC (descending) . The following example creates a View and apply sort on the column Product_Price in descending order. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Sort DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price > 100", "Product_Price Desc",

DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to Filter DataView


DataView enables you to create different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable. DataView can be used to sort, filter, and search a DataTable , additionally we can add new rows and modify the content in a DataTable. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. Also we can create multiple DataViews for any given DataTable. The following source code creates a view that shows all Product Details where the Product Price less than 500. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open()

command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Filter DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price < = 500", "Product_Name", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to Find a row in DataView


The DataView provides different views of the data stored in a DataTable. The constructor for the DataView class initializes a new instance of the DataView class and accepts the DataTable as an argument. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable. We can search in a DataView according to the sort key values by using the Find method . The Find method returns an integer with the index of the DataRowView that matches the search criteria. If more than one row matches the search criteria, only the index of the first matching DataRowView is returned. If no matches are found, Find returns -1 Dim index As Integer = DataView.Find("Product5")
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand

adapter As New SqlDataAdapter ds As New DataSet dv As DataView sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Find Row DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_id").ToString() & " End If Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dim Dim Dim Dim

" & dv(index)("Product_Name").ToString())

How to add new rows in DataView


The DataView provides different views of the data stored in a DataTable. DataViews can be created and configured at both design time and run time . We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable.

We can add new rows in the DataView using AddNew method in the DataView. The following source code shows how to add new row in a DataView . Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Add New") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) Dim newRow As DataRowView = dv.AddNew() newRow("Product_ID") = 7 newRow("Product_Name") = "Product 7" newRow("Product_Price") = 111 newRow.EndEdit() dv.Sort = "product_id" DataGridView1.DataSource = dv

Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to update rows in DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search a DataTable , additionally we can add new rows and modify the content in a DataTable. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. Also we can create multiple DataViews for any given DataTable. We can update the data in a DataView . The following source code shows how to update data in a DataView . Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Update")

adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_Name", DataViewRowState.CurrentRows) Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Product not found") Else dv(index)("Product_Name") = "Product11" MsgBox("Product Updated !") End If DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to delete rows in DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the content in a DataTable. Also we can delete the data from the DataView . The following source code shows how to delete the data from DataView.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView

Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Delete Row") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_ID", DataViewRowState.CurrentRows) dv.Table.Rows(3).Delete() DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to create a new DataTable from DataView


The DataView provides different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable. Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing that DataTable. We can create a new DataTable from the DataView . We can use the ToTable method to copy all the rows and columns, or a subset of the data into a new DataTable.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand

adapter As New SqlDataAdapter ds As New DataSet dv As DataView sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Copy to DataTable") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price <= 200", "Product_ID", DataViewRowState.CurrentRows) Dim dTable As DataTable dTable = dv.ToTable DataGridView1.DataSource = dTable Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dim Dim Dim Dim

VB.NET REMOTING TUTORIALS

VB.NET Remoting Tutorial


The .NET Remoting supports Distributed Object communications over the TCP and HTTP transports by using Binary or SOAP representation of the data stream. From the following links you can see the components in .Net Remoting in detail.

.Net Remoting Architecture


The .NET Remoting provides an inter-process communication between Application Domains by using Remoting Framework. The applications can be located on the same computer, different computers on the same network, or on computers across separate networks. The .NET Remoting supports distributed object communications over the TCP and HTTP channels by using Binary or SOAP formatters of the data stream.

The main three components of a Remoting Framework are : 1. Remotable Object. 2. Remote Listener Application - (listening requests for Remote Object) 3. Remote Client Application - (makes requests for Remote Object)
The Remote Object is implemented in a class that derives from System.MarshalByRefObject .

.Net Remoting Architecture


The .NET Remoting provides an inter-process communication between Application Domains by using Remoting Framework. The applications can be located on the same computer, different computers on the same network, or on computers across separate

networks. The .NET Remoting supports distributed object communications over the TCP and HTTP channels by using Binary or SOAP formatters of the data stream. The main three components of a Remoting Framework are : 1. Remotable Object. 2. Remote Listener Application - (listening requests for Remote Object) 3. Remote Client Application - (makes requests for Remote Object) The Remote Object is implemented in a class that derives from System.MarshalByRefObject .

You can see the basic workflow of .Net Remoting from the above figure. When a client calls the Remote method, the client does not call the methods directly . It receives a proxy to the remote object and is used to invoke the method on the Remote Object. Once the proxy receives the method call from the Client , it encodes the message using appropriate formatter (Binary Formatter or SOAP Formatter ) according to the Configuration file. After that it sends the call to the Server by using selected Channel (TcpChannel ,HttpChannel). The Server side channel receives the request from the proxy and forwards it to the Server on Remoting system, which

locates and invokes the methods on the Remote Object. When the execution of remote method is complete, any results from the call are returned back to the client in the same way. Before an object instance of a Remotable type can be accessed, it must be created and initialized by a process known as Activation. Activation is categorized in two models , they are Client-activated Objects and Server-activated Objects. Remote Activation The real difference between client-activated and server-activated objects is that a server-activated object is not really created when a client instantiates it. Instead, it is created as needed. By default the .NET Framework ships with two formatters(Binary Formatter or SOAP Formatter ) and two channels(TcpChannel ,HttpChannel). Remote Channels Remote Formatters Formatters and Channel are configured by using Configuration files. It can be easily Configured by using XML-based files. Remote Configuration
The .NET Remoting is easy to use and powerful, largely because it is based on the Common Type System (CTS) and the Common Language Runtime (CLR). From the following link , you can understand .Net Remoting components in detail.

VB.NET Remoting Apllication


The .NET Remoting supports Distributed Object communications over the TCP and HTTP transports by using Binary or SOAP representation of the data stream. For building a Remoting application in VB.NET ,you must have an implementation of a Remotable type, a Listening or Host Application domain, a Client or calling application domain, and you must Configure the remoting system in each application domain to use remote activation for the remotable type.

Remotable Object Remote Listener Application Remote Client Application Remote Configuration

Remotable Type
Any object outside the application domain of the caller application should be considered as Remote Object. A Remote Object that should be derived from MarshalByRefObject Class. Any object can be changed into a Remote Object by deriving it from MarshalByRefObject . Objects without inheriting from MarshalByRefObject are called Non-remotable Objects. The following example creating a Remote Object in VB.Net, RemoteTime , which send the current time to the Client Application using Remoting Framework. The RemoteTime class is derived from MarshalByRefObject and inside the class it has a method getTime() which return the current time from Remote Object. Download Source Code
Imports System Public Class RemoteTime Inherits MarshalByRefObject Private currentTime As String = "" Public Function getTime() As String currentTime = DateTime.Now.ToShortTimeString() Return "Remote Server Time : " & currentTime End Function End Class

Print Source Code

Copy and paste the above VB.Net source code into a file and save it as RemoteTime.vb Compile the class RemoteTime.vb into a library using the command-line tools that ship with the .NET Framework SDK.

At the command prompt in the directory in which you saved the file, type the following command: vbc /t:library RemoteTime.vb After you compile the RemoteTime.vb , you will get a file called RemoteTime.dll in the directory which you saved the source file.

Remote Listener Application


We already created a Remote Type Object RemoteTime in the previous section. We have to create a listener Object for enable Objects in other application domains to create instances of this object (RemoteTime) Remotely. When creating a listener Object we have to choose and register a channel for handle the networking protocol and serialization formats and register the Type with the .NET Remoting system, so that it can use the channel to listen for requests for the Type. Channels are Objects that responsible of handling the network protocols and serialization formats. In the following example we are creating a listener application TimeListener . It will act as a listener Object for the Remote Type RemoteTime. The Listener class TimeListener must be able to find the TimeListener.exe.config file to load the configuration for the RemotableType class.
Download Source Code
Imports System Imports System.Runtime.Remoting Public Class TimeListener Public Shared Sub Main() RemotingConfiguration.Configure("TimeListener.exe.config") Console.WriteLine("Listening for requests from the Client. Press Enter to exit...") Console.ReadLine() End Sub End Class

Print Source Code

Copy and paste the above VB.Net source code into a file and save it as TimeListener.vb. We have to create additional configuration file to provide the communication information to the listener Object. The configuration file is an XML structured file. We can specify the Activation Mode , the Remote Type , Channel , port for communication etc. through the configuration file .

Click here to download TimeListener.exe.config . Compile the class file TimeListener.vb using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /r:RemoteTime.dll TimeListener.vb After you compile the TimeListener.vb , you will get a file called TimeListener.exe in the directory which you saved the source file

Remote Client Application


The Client application for calling Remote Object's method in VB.Net is pretty simple and straight forward. The .NET Remoting system will intercept the client calls, forward them to the remote object, and return the results to the client. The Client Application have to register for the Remote Type also.

Here in the Client application in VB.Net , creating an instance of the Remote Type, RemoteTime Object , and call the method getTime() . Aditionally it uses the configuration file Client.exe.config for the communication information for the Remoting Framework.
Download Source Code
Imports System Imports System.Runtime.Remoting Public Class Client Public Shared Sub Main() RemotingConfiguration.Configure("Client.exe.config") Dim remoteTimeObject As New RemoteTime() Console.WriteLine(remoteTimeObject.getTime()) End Sub End Class

Print Source Code

Copy and paste the above VB.Net source code into a file and save it as Client.vb. We have to create additional configuration file to provide the communication information to the Client Object. The configuration file is a an XML structured file. We can specify the Remote Type , Channel , port for communication etc. through the configuration file .

Click here to download Client.exe.config . Compile the class file Client.vb using the command-line tools that ship with the .NET Framework SDK.

At the command prompt in the directory in which you saved the file, type the following command: vbc /r:RemoteTime.dll Client.vb After you compile the Client.vb , you will get a file called Client.exe in the directory which you saved the source file

Compiling and Running Remote Application


The .NET Remoting is one of several ways to establish communication between application domains using the .NET Framework. The main three components of a Remoting Framework are a Remotable Object , Listener Application for listening requests for remote object and a Client Application makes requests for remote object. Additionally you need Configuration files for your Listener Application and Client Application. Compiling the VB.Net source code files Create a new folder SRC and put the three VB.Net source code files in that folder. 1. RemoteTime.vb 2. TimeListener.vb 3. Client.vb Add the two configuration files in the same folder. 1. TimeListener.exe.config 2. Client.exe.config Compile these VB.Net class files using the command-line tools that ship with the .NET Framework SDK.

vbc /t:library RemoteTime.vb vbc /r:RemoteTime.dll TimeListener.vb vbc /r:RemoteTime.dll Client.vb Note: You have to provide the physical path of each source files when you compile the source code , for example : if the source code files are in the folder c:\SRC , you have to give path like vbc /r:c:\SRC\RemoteTime.dll c:\SRC\TimeListener.vb After you complied the VB.Net source code files, you will get additional three files in the SRC folder. They are : RemoteTime.dll TimeListener.exe Client.exe To run the application Create two new folders and give the name like Server and Client respectively. Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the Server folder. Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder. Open a command prompt on Server folder and type TimeListener Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..." Open a command prompt on Client folder and type Client.

Then you will get the current time from remote Object. Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more on Remoting ...

Remoting Configurations
Configuration provides the necessary information to .Net Remoting Framework . We can provide .Net Remoting configuration parameters in two ways. Either we can provide the information to the Server and the Client directly by program coding or through a Machine.config file. Using configuration file give better advantage over coding because the parameters of remote object can be configured without changing any program coding and avoid recompile the source code. Following are the information provided by configuration file : Metadata describing the Remote Type Type of Activation Channels The URL that uniquely identifies the object of that type. We have to provide configuration information to Listener Object and also Client Object . Listener Configuration

Click here to download TimeListener.exe.config . Client Configuration

Click here to download Client.exe.config .

Remoting Activation

The .Net Remoting framework supports Server and Client activation of Remote Objects. Before an Object instance of a Remotable type can be accessed, it must be created and initialized by Activation process. There are commonly two types of activation modes : Server Activation and Client Activation mode. Server activation is normally used when a Remote objects is not required to maintain any state between method calls. Client Activated objects are instantiated from the client, and the client manages the lifetime of the Remote Object by using a lease-based system provided for that purpose. SingleCall Objects and Singleton Objects belong to Server Activation mode. For SingleCall objects the server will create a single object, execute the method, and destroy the object again. On the other hand with Singleton mode only one object is created at all. Singleton objects can be used to share information between multiple clients. The real distinction between Client Activated and Server Activated object is that a server-activated object is not really created when a client instantiates it. Instead, it is created as needed.

Remoting Channel
In .Net Remoting Channels are used to transport messages to and from the Remote Objects. Channels are Objects that responsible of handling the network protocols and serialization formats. In .Net Remoting channel can be implement either by calling the method ChannelServices.RegisterChannel or by using configuration file. Channels should be registered before objects are registered. When a channel is registered, it automatically starts listening for client requests at the specified port. At least one channel must be registered with the remoting framework before a Remote object can be called. There are two types of Channels available in .Net Remote Framework: HTTP channel and TCP channel. The HTTP channel transports messages to and from remote objects using the SOAP protocol. The TCP channel uses a binary formatter to serialize all messages to a binary stream and transport the stream to the target URI using the TCP protocol.

Remoting Channel
Formatters are used for encoding and decoding the messages before they are transported by the Channel in .Net Remoting Framework. The .Net Remoting Framework supports two types of Formatters : Binary Formatter System.Runtime.Serialization.Formatters.Binary and SOAP Formatter - System.Runtime.Serialization.Formatters.Soap . The data in binary Formatter has smaller size when compared to SOAP Formatter. The SOAP Formatter is an XML based cross platform text format , so it can be human readable. The data in a SOAP Formatter larger size compared to Binary Formatter , so it can therefore reduce overall performance. VB.NET ADO.NET DATASET TUTORIALS

VB.NET ADO.NET Dataset Tutorial


The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection . It represents a collection of data retrieved from the Data Source. We can use Dataset in combination with DataAdapter class. The DataSet object offers a disconnected data source architecture. The following link gives you in details about Dataset.

What is ADO.NET Dataset


The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection . It represents a collection of data retrieved from the Data Source. We can use Dataset in combination with DataAdapter class. The DataSet object offers a disconnected data source architecture. The Dataset can work with the data it contain, without knowing the source of the data coming from. That is , the Dataset can work with a disconnected mode from its Data Source . It gives a better advantage over DataReader , because the DataReader is working only with the connection oriented Data Sources.

The Dataset contains the copy of the data we requested. The Dataset contains more than one Table at a time. We can set up Data Relations between these tables within the DataSet. The data set may comprise data for one or more members, corresponding to the number of rows.

The DataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method of the DataAdapter for populating data in a Dataset. The DataSet can be filled either from a data source or dynamically. A DataSet can be saved to an XML file and then loaded back into memory very easily. The following links shows more information of Dataset in details.

How to Dataset with Sql Server


The DataSet contains the copy of the data we requested through the SQL statement. We can use Dataset in combination with SqlDataAdapter class . The SqlDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User

ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) adapter.Dispose() command.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -" & ds.Tables(0).Rows(i).Item(1))

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to Dataset with OLEDB Data Source


The DataSet contains the copy of the data we requested through the SQL statement. We can use Dataset in combination with OleDbDataAdapter class . The OleDbDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -" & ds.Tables(0).Rows(i).Item(1))

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

Search Tables in a Dataset Sql Server

The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The Dataset may comprise data for one or more members, corresponding to the number of rows. The SqlDataAdapter object allows us to populate DataTables in a DataSet. In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim tables As DataTable Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() For Each tables In ds.Tables MsgBox(tables.TableName)

Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

Search Tables in a Dataset OLEDB Data Source


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data inside Table is in the form of Rows and Columns . The OleDbDataAdapter object allows us to populate DataTables in a DataSet. In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here"

connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables.Count - 1 MsgBox(ds.Tables(i).TableName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

Dataset table row count in SQL Server


The DataSet contains copy of the data we requested through the SQL statement. The DataSet consists of DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data set may comprise data for one or more members, corresponding to the number of rows. The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String

Dim Dim Dim Dim Dim

connection As SqlConnection command As SqlCommand adapter As New SqlDataAdapter ds As New DataSet sql As String

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() MsgBox("Number of row(s) " & ds.Tables(0).Rows.Count)

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

Dataset table row count - OLEDB Data Source

The DataSet contains copy of the data we requested through the SQL statement. The DataSet consists of DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data inside Table is in the form of Rows and Columns . The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset from OLEDB Data Source. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() MsgBox("number of Row(s) " & ds.Tables(0).Rows.Count)

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here"

You have to replace the string with your real time variables.

How to find column definition - Sql Server


Dataset represents a collection of data retrieved from the Data Source. The Dataset can work with the data it contains, without knowing the source of the data coming from. The SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset. The Dataset can contains more than one Table at a time. The data inside Table is in the form of Rows and Columns . In some situations we have to find the column headers in a DataTable. There is a ColumnsCollection object in the Datatable hold the column Definitions.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim column As DataColumn Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table")

adapter.Dispose() command.Dispose() connection.Close() dt = ds.Tables(0) For Each column In dt.Columns MsgBox(column.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to find column definition - OLEDB Data Source


Dataset represents a collection of data retrieved from the Data Source.. The OleDbDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. The Dataset can contain more than one Table at a time. The data set may comprise data for one or more members, corresponding to the number of rows. In some situations we have to find the column headers in a DataTable. There is a ColumnsCollection object in the Datatable hold the column Definitions.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection

Dim Dim Dim Dim Dim

oledbAdapter As OleDbDataAdapter ds As New DataSet dt As DataTable sql As String i As Integer

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() dt = ds.Tables(0) For i = 0 To dt.Columns.Count - 1 MsgBox(dt.Columns(i).ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to create DataSet without Databse


Dataset represents a collection of data retrieved from the Data Source. The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data set may comprise data for one or

more members, corresponding to the number of rows. We can fill the data in Dataset without calling SQL statements. For that we manually create a DataTable and add data in it.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim dt As DataTable Dim dr As DataRow Dim idCoulumn As DataColumn Dim nameCoulumn As DataColumn Dim i As Integer dt = New DataTable() idCoulumn = New DataColumn("ID", Type.GetType("System.Int32")) nameCoulumn = New DataColumn("Name", Type.GetType("System.String")) dt.Columns.Add(idCoulumn) dt.Columns.Add(nameCoulumn) dr = dt.NewRow() dr("ID") = 1 dr("Name") = "Name1" dt.Rows.Add(dr) dr = dt.NewRow() dr("ID") = 2 dr("Name") = "Name2" dt.Rows.Add(dr) ds.Tables.Add(dt) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next i End Sub -" & ds.Tables(0).Rows(i).Item(1))

End Class

How to multiple tables in Dataset - Sql Server


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The SqlDataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using SqlDataAdapter Object . The following VB.NET source code shows how to a single SqlDataAdapter fill Dataset with multiple tables.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "First Table")

adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Second Table") adapter.Dispose() command.Dispose() connection.Close() 'retrieve first table data For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next 'retrieve second table data For i = 0 To ds.Tables(1).Rows.Count - 1 MsgBox(ds.Tables(1).Rows(i).Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

--

" & ds.Tables(0).Rows(i).Item(1))

--

" & ds.Tables(1).Rows(i).Item(1))

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to multiple tables in Dataset - OLEDB Data Source


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The OleDbDataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using OleDbDataAdapter Object . The following VB.NET source code shows how to a single OleDbDataAdapter fill Dataset with multiple tables.

Download Source Code

Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(firstSql, connection) oledbAdapter.Fill(ds, "First Table") oledbAdapter.SelectCommand.CommandText = secondSql oledbAdapter.Fill(ds, "Second Table") oledbAdapter.Dispose() connection.Close() 'retrieve first table data For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " & ds.Tables(0).Rows(i).Item(1)) Next 'retrieve second table data For i = 0 To ds.Tables(1).Rows.Count - 1 MsgBox(ds.Tables(1).Rows(i).Item(0) & " -- " & ds.Tables(1).Rows(i).Item(1)) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"

firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.

How to add relations between tables in a Dataset


The DataSet contains DataTableCollection and their DataRelationCollection. The DataSet.Relations property is an instance of the DataRelationsCollection Object. We can create parent child data relations between DataTable using Datarelation Object. We can relate one or more column from different tables using DataRelation Object . The columns involved in the DataRelation should be identical data types. That is the parent and child column should be similar Data Types.
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table1") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table2")

adapter.Dispose() command.Dispose() connection.Close() 'creating data relations Dim relation As DataRelation Dim table1Column As DataColumn Dim table2Column As DataColumn 'retrieve column table1Column = ds.Tables("Table1").Columns(0) table2Column = ds.Tables("table2").Columns(0) 'relating tables relation = New DataRelation("relation", table1Column, table2Column) 'assign relation to dataset ds.Relations.Add(relation) MsgBox("Data relation completed") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.

How to merge tables in a Dataset - Sql Server


The DataSet contains copy of the data we requested through the SQL statement. The SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using SqlDataAdapter Object. The DataTableCollection contains zero or more DataTable objects.

In some situation we want to combine the result of multiple SQL query as a single result set. In that case we can use the Dataset's Merge method for doing this. The tables involved in the merge should be identical, that is the columns are similar data types .
Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table(0)") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table(1)") adapter.Dispose() command.Dispose() connection.Close() ds.Tables(0).Merge(ds.Tables(1)) dt = ds.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " Next -" & dt.Rows(i).Item(1))

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.

How to merge tables in a Dataset - OLEDB Data Source


The DataSet contains copy of the data we requested through the SQL statement. The OleDbDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using OleDbDataAdapter Object. The DataTableCollection contains zero or more DataTable objects. In some situation we want to combine the result of multiple SQL query results as a single result set. In that case we can use the Dataset's Merge method for doing this. The tables involved in the merge should be identical. The following VB.NET source code shows how to merge the tables from two different dataset.
Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds1 As New DataSet Dim ds2 As New DataSet Dim dt As DataTable Dim firstSql As String Dim secondSql As String Dim i As Integer

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(firstSql, connection) oledbAdapter.Fill(ds1, "First Table") oledbAdapter.SelectCommand.CommandText = secondSql oledbAdapter.Fill(ds2, "Second Table") oledbAdapter.Dispose() connection.Close() ds1.Tables(0).Merge(ds2.Tables(0)) dt = ds1.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " Next -" & dt.Rows(i).Item(1))

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.

Insert image in a database


ADO.NET provides database connectivity between relational and non relational systems through a common set of components . SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server. Image is a Datatype in

SQL Server that stores variable length binary data from 0 through 2A31-1 (2,147,483,647) bytes. The following VB.NET program shows how to insert an Image in SQL Server. First you have to create a table that contain an image column . The following sql script help you to create a table with Image Datatype column :
CREATE TABLE [dbo].[imgtable]( [id] [int] NULL, [img] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

The above scrip will create a table named as imgtable and adding two column , first column is id ,an integer datatype and second column is image, an image(img) datatype. The following VB.NET source code read the image from physical path D:\picfile.jpg and stores it to a byte array and then insert it into database. Download Source Code
Imports System.Data.SqlClient Imports System.IO Public Class Form1 Dim fName As String Dim cnn As SqlConnection Dim connectionString As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password" cnn = New SqlConnection(connectionString) fName = "D:\picfile.jpg" If File.Exists(fName) Then Dim id As Integer = 1 Dim content As Byte() = ImageToStream(fName) cnn.Open()

Print Source Code

Dim cmd As New SqlCommand("insert into imgtable (id,img) values ( @id,@img)", cnn) cmd.Parameters.AddWithValue("@id", id) cmd.Parameters.AddWithValue("@img", content) cmd.ExecuteNonQuery() cnn.Close() MsgBox("Image inserted") Else MsgBox(fName & " not found ") End If End Sub Private Function ImageToStream(ByVal fileName As String) As Byte() Dim stream As New MemoryStream() tryagain: Try Dim image As New Bitmap(fileName) image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg) Catch ex As Exception GoTo tryagain End Try Return Stream.ToArray() End Function End Class

Retrieve image from database


Managed Providers are a collection of classes in the .NET Framework that provide a foundation for the ADO.NET programming model. A data type is an attribute that specifies the type of data that the object can hold: integer data, character data, date and time data, image data and so on. Conversion of image data type to another data type is not supported, implicitly or explicitly. However, indirect conversion of image data can be performed.
Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte())

The following VB.NET source code shows how to retrieve an image from SQL Server. Download Source Code
Imports System.IO Imports System.Data.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password" cnn = New SqlConnection(connectionString) Dim stream As New MemoryStream() cnn.Open() Dim command As New SqlCommand("select img from imgtable where id=1", cnn) Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte()) stream.Write(image, 0, image.Length) cnn.Close() Dim bitmap As New Bitmap(stream) PictureBox1.Image = bitmap End Sub End Class

Print Source Code

VB.NET XML TUTORIALS

VB.NET XML Tutorial


XML is a self describing language and it gives the data as well as the rules to identify what information it contains. Like HTML , XML is a subset of SGML - Standard Generalized Markup Language. The following links give you more information about XML Files and its operations through VB.NET .

How to XML in VB.NET


XML is a general purpose tag based language and very easy to transfer and store data across applications. Like HTML , XML is a subset of SGML - Standard Generalized Markup Language. XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify what information it contains. XML files are made up of tags that contains data. Generally a start tag and end tag to hold the data. For example, if you want to create an XML tag name "Header" , the start tag is like < Header > and the end tag is like < /Header > . We can fill our information between these tags. < Header > Header Content Here < /Header > While creating an XML file , some important points have to remember : * XML is case sensitive ex: < Header > is not same as < HeadeR > . * Tags must be closed in the reverse order that they were opened ex : < first-tag >< second-tag > Data here < /second-tag > < /first-tag > Sample XML File

The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . These classes are stored in the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal storage format. You can use any text editor to create an XML file . More over XML files are readable by humans as well as computers. From the following links you can see how to use XML in VB.NET.
Working Effectively with Legacy Code Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more... Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details

How to create an XML file in VB.NET


XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). If we create an XML file in one platform it can be used in other platforms also. For creating a new XML file in VB.NET, we are using XmlTextWriter class . The class takes FileName and Encoding as argument. Also we are here passing formating details . The following source code creating an XML file product.xml and add four rows in the file.
Download Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details. Print Source Code Download Free CMS for ASP.NET Easily develop websites, intranets, social networks and e-shops. Download Now!

Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim writer As New XmlTextWriter("product.xml", System.Text.Encoding.UTF8) writer.WriteStartDocument(True) writer.Formatting = Formatting.Indented writer.Indentation = 2 writer.WriteStartElement("Table") createNode(1, "Product 1", "1000", writer) createNode(2, "Product 2", "2000", writer) createNode(3, "Product 3", "3000", writer) createNode(4, "Product 4", "4000", writer) writer.WriteEndElement() writer.WriteEndDocument() writer.Close() End Sub Private Sub createNode(ByVal pID As String, ByVal pName As String, ByVal pPrice As String, ByVal writer As XmlTextWriter)

writer.WriteStartElement("Product") writer.WriteStartElement("Product_id") writer.WriteString(pID) writer.WriteEndElement() writer.WriteStartElement("Product_name") writer.WriteString(pName) writer.WriteEndElement() writer.WriteStartElement("Product_price") writer.WriteString(pPrice) writer.WriteEndElement() writer.WriteEndElement() End Sub End Class

Output of the above source code :

How to open and read an XML file in VB.NET

XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the information embedded in XML tags in an XML file. In the previous program we create an XML file and named it as products.xml. The following program read that file and extract the contents inside the XML tag. We can read an XML file in several ways depends on our requirement. This program read the content in Node wise . Here we are using XmlDataDocument class to read the XML file . In this program it search the Node < Product > and its child Nodes and extract the data in child nodes.
Download Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms spreadsheet controls, Excel compatible charting, the fastest and most complete Excel compatible calculations and more Print Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details

Imports System.Xml Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmldoc As New XmlDataDocument() Dim xmlnode As XmlNodeList Dim i As Integer Dim str As String Dim fs As New FileStream("products.xml", FileMode.Open, FileAccess.Read) xmldoc.Load(fs) xmlnode = xmldoc.GetElementsByTagName("Product") For i = 0 To xmlnode.Count - 1 xmlnode(i).ChildNodes.Item(0).InnerText.Trim() str = xmlnode(i).ChildNodes.Item(0).InnerText.Trim() & " | " & xmlnode(i).ChildNodes.Item(1).InnerText.Trim() & " | " & xmlnode(i).ChildNodes.Item(2).InnerText.Trim() MsgBox(str) Next End Sub End Class

Click here to download the input file product.xml

<?xml version="1.0" encoding="UTF-8" standalone="true"?> <Table><Product><Product_id>1</Product_id><Product_name>Product 1</Product_name><Product_price>1000</Product_price></Product><Product><Product_id>2</Product_id><Product_name>Product 2</Product_name><Product_price>2000</Product_price></Product><Product><Product_id>3</Product_id><Product_name>Product 3</Product_name><Product_price>3000</Product_price></Product><Product><Product_id>4</Product_id><Product_name>Product 4</Product_name><Product_price>4000</Product_price></Product></Table>

How to create an XML file in VB.NET using Dataset


XML is a tag based language, that means the document is made up of XML tags that contain information. We can create an XML file in several ways. In the previous section we create an XML file using XmlTextWriter Class. Here we are creating an XML file Product.XML using an ADO.NET Dataset. For that we have to manually create a Datatable first and add the data of Product.XML in the Datatable . Then add the Datatable in a Dataset . Call the method WriteXml of Dataset and pass the file name Product.XML as argument.
Download Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.
Imports System.Xml

Print Source Code SpreadsheetGear: ASP.NET Excel Reporting Easily create richly formatted Excel reports without Excel using the new generation of spreadsheet technology built from the ground up for scalability and reliability. Learn more

Imports System.Data Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet dt = New DataTable() dt.Columns.Add(New DataColumn("Product_ID", Type.GetType("System.Int32"))) dt.Columns.Add(New DataColumn("Product_Name", Type.GetType("System.String"))) dt.Columns.Add(New DataColumn("product_Price", Type.GetType("System.Int32"))) fillRows(1, "product1", 1111) fillRows(2, "product2", 2222) fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" ds.WriteXml("Product.xml") MsgBox("Done") End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class

How to read an XML file in VB.NET using ADO.NET - Dataset


XML is a platform independent language, so the information formatted in XML can be use in any other platforms (Operating Systems) . The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .

In the previous section we already saw how to read an XML file through Node navigation . Here we are going to read an XML file using an DataSet. Here Dataset is using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. Click here to download the input file product.xml
Download Source Code SpreadsheetGear: ASP.NET Excel Reporting Easily create richly formatted Excel reports without Excel using the new generation of spreadsheet technology built from the ground up for scalability and reliability. Learn more Print Source Code The Android Developer's Cookbook Want to get started building applications for Android? Already building Android applications and want to get better at it? This book brings together all the expert guidanceand codeyoull need!

Imports System.Xml Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) Dim i As Integer For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next End Sub End Class

How to create an XML file from SQL in VB.NET


XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format.

There are several ways to create an XML file . In the previous sections we already saw how to create an XML file using XmlTextWriter and also created an XML file using manually created Dataset. Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as argument.
Download Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms spreadsheet controls, Excel compatible charting, the fastest and most complete Excel compatible calculations and more Print Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.

Imports System.Xml Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(sql, connection) adapter.Fill(ds) connection.Close() ds.WriteXml("Product.xml") MsgBox("Done") Catch ex As Exception MsgBox(ex.ToString) End Try

End Sub End Class

You have to pass necessary database connection information to connection string.

How to search in an XML file


XML files are made up of tags that contains information. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format. The following source code shows how to search an item in an XML file using Dataset . Here Dataset using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. By using the Dataset , search the product Product2 in the file Product.XML with the help of DataView.
Download Source Code Print Source Code Proven Distributed Data Grid Dont trust your mission-critical apps to first generation distributed caches. ScaleOut StateServer is in production use - now - at hundreds of companies worldwide. Download a free evaluation copy!
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product2") If index = -1 Then

MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_Name").ToString() & " End If End Sub " & dv(index)("Product_Price").ToString())

Click here to download the input file product.xml

How to filter data in an XML file


XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). If we create an XML file in one platform it can be used in other platforms also. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format. Here we are going to filter an XML file content and store the result in a newly created XML file. We have an XML file Product.XML , and it has a field Product_Price. We are giving a search criteria like the Product_Price >= 3000 and store the result in a newly created XML file Result.XML.
Download Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms spreadsheet controls, Excel compatible charting, the fastest and most complete Excel compatible calculations and more Print Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.

Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView

ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0), "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows) dv.ToTable().WriteXml("Result.xml") MsgBox("Done") End Sub End Class

Click here to download the input file product.xml

How to insert data from xml to database


XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format. Here we are going to insert the values of an XML file to a Database Table using SQL insert command. Here the Dataset using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. Also establish a connection to the Database using a connectionstring . After getting the data from XML file to the Dataset , we can loop through the dataset values and use insert command to add the values to the Product table in the Databse.
Download Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details Print Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details

Imports System.Xml Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String

Dim Dim Dim Dim Dim Dim

connection As SqlConnection command As SqlCommand adpter As New SqlDataAdapter ds As New DataSet xmlFile As XmlReader sql As String

Dim product_ID As Integer Dim Product_Name As String Dim product_Price As Double connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString) xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile) Dim i As Integer connection.Open() For i = 0 To ds.Tables(0).Rows.Count - 1 product_ID = Convert.ToInt32(ds.Tables(0).Rows(i).Item(0)) Product_Name = ds.Tables(0).Rows(i).Item(1) product_Price = Convert.ToDouble(ds.Tables(0).Rows(i).Item(2)) sql = "insert into Product values(" & product_ID & ",'" & Product_Name & "'," & product_Price & ")" command = New SqlCommand(sql, connection) adpter.InsertCommand = command adpter.InsertCommand.ExecuteNonQuery() Next connection.Close() End Sub End Class

You have to pass necessary database connection information to connection string. Click here to download the input file product.xml

How to create an Excel file from XML

XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify what the data it contains. Here we are going to read from an XML file content and write the same content to an Excel file. Using an XmlReader for read the XML file to the Dataset . Loop through the Dataset and add the content to the Excel file . For create an excel file you have to add reference of Excel library to you project .
Download Source Code Print Source Code

Introducing HTML5 (Voices that Matter) Take our 3-Minute Hosting Decisions Survey Concentrating on the practical and the issues that HTML5 can solve Participants will be eligible to win a $100 Amazon gift certificate. Take "Introducing HTML5" is written by developers who have been using the the short survey here. new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
Imports System.Xml Imports System.Data Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim ds As New DataSet Dim xmlFile As XmlReader Dim i, j As Integer xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile)

For i = 0 To ds.Tables(0).Rows.Count - 1 For j = 0 To ds.Tables(0).Columns.Count - 1 xlWorkSheet.Cells(i + 1, j + 1) = _ ds.Tables(0).Rows(i).Item(j) Next Next xlWorkSheet.SaveAs("xml2excel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub End Class

Click here to download the input file product.xml

How to create an XML file from Excel


XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .

The following program shows how to create an XML file from an Excel file content . Here we are using an OleDbConnection to read the excel file and store the content to a Dataset . Call the method WriteXml of Datset to write to the XML file.
Download Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details Print Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.

Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim MyConnection As System.Data.OleDb.OleDbConnection Dim ds As System.Data.DataSet Dim MyCommand As System.Data.OleDb.OleDbDataAdapter MyConnection = New System.Data.OleDb.OleDbConnection _ ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='xl2xml.xls';Extended Properties=Excel 8.0;") MyCommand = New System.Data.OleDb.OleDbDataAdapter _ ("select * from [Sheet1$]", MyConnection) MyCommand.TableMappings.Add("Table", "Product") ds = New System.Data.DataSet MyCommand.Fill(ds) MyConnection.Close() ds.WriteXml("Product.xml") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Click here to download the input excel file xl2xml.xls

How to xml to DataGridView

XML is a platform independent language, so the information formatted in XML file can be use in any other platforms . The .Net technology is widely supported XML file format. The following source code shows , how to load data in a DataGridView from an XML file . Here the Dataset using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. When the Dataset retrieves the data, it passes as DataSource to DataGridView .
Download Source Code Professional Code Generator Free for personal usage Ensure rock-solid foundations for your application while focusing on features, not plumbing. ASP.NET, Silverlight, WPF, Winforms, Phone or Azure. Print Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details

Imports System.Xml Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) DataGridView1.DataSource = ds.Tables(0) End Sub End Class

Click here to download the input file product.xml

How to create a TreevView from XML


XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the data embedded in tags in an XML file.

In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes data to TreeView.
Download Source Code Download Free CMS for ASP.NET Easily develop websites, intranets, social networks and e-shops. Download Now! Print Source Code Professional Code Generator Free for personal usage Ensure rock-solid foundations for your application while focusing on features, not plumbing. ASP.NET, Silverlight, WPF, Winforms, Phone or Azure.

Imports System.Xml Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmldoc As New XmlDataDocument() Dim xmlnode As XmlNode

Dim fs As New FileStream("tree.xml", FileMode.Open, FileAccess.Read) xmldoc.Load(fs) xmlnode = xmldoc.ChildNodes(1) TreeView1.Nodes.Clear() TreeView1.Nodes.Add(New TreeNode(xmldoc.DocumentElement.Name)) Dim tNode As TreeNode tNode = TreeView1.Nodes(0) AddNode(xmlnode, tNode) End Sub Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As TreeNode) Dim xNode As XmlNode Dim tNode As TreeNode Dim nodeList As XmlNodeList Dim i As Integer If inXmlNode.HasChildNodes Then nodeList = inXmlNode.ChildNodes For i = 0 To nodeList.Count - 1 xNode = inXmlNode.ChildNodes(i) inTreeNode.Nodes.Add(New TreeNode(xNode.Name)) tNode = inTreeNode.Nodes(i) AddNode(xNode, tNode) Next Else inTreeNode.Text = inXmlNode.InnerText.ToString End If End Sub End Class

Click here to download the input file tree.xml

How to create Crystal Reports from XML


XML is a self describing language and it gives the data as well as the rules to identify what the data it contains. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . We can use XML as a Data Source to Crystal Reports like a Database . Click here to see, How to create Crystal Reports from xml .

Crystal Reports from XML File


In this section you can see , creating a Crystal Reports from XML file instead of database . This is very similer to creating Crystal Reports from database , the only difference is to sslect the data source as your XML file. Here we are creating an XML file name is Product is XML file the same structure of the Product table in the sample Database Structure. Download Product.XML

The basics of Crystal Reports creation provided in previous tutorials , if you dont have much knowledge in Crystal Reports , take a look at the tutorial step by step Crystal Report before start this section. The change happen only from previous report , when you select Data for Crsyatl Report , you have to select Create New Connection Database Files and select the XML file you want to generate Crystal Reports (In this case you select the Product.xml ).

Select all the fields from Product and click finish button Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program .
Download Source Code Print Source Code

Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class

cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here.

How to serialization in xml


XML Serialization is the process of serializing a .Net Object to the form of XML or from an XML to .Net Object. The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. This is the process of converting an object into a form that can be readily transported. During XML serialization, only the public properties and fields of an object are serialized. The following links gives you more details about XML Serialization and De-serialization. How to serialize a .Net Object to XML How to de-serialize XML to .Net Object

How to serialize a .Net Object to XML


Serialization of XML to common language runtime objects enables one to convert XML documents into a form where they are easier to process using conventional programming languages. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .

The following program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer class for serialize the Dataset Object.
Download Source Code Print Source Code

Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet dt = New DataTable() dt.Columns.Add(New DataColumn("Product_ID", Type.GetType("System.Int32"))) dt.Columns.Add(New DataColumn("Product_Name", Type.GetType("System.String"))) dt.Columns.Add(New DataColumn("product_Price", Type.GetType("System.Int32"))) fillRows(1, "product1", 9999) fillRows(2, "product2", 2222) fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" Dim serialWriter As StreamWriter serialWriter = New StreamWriter("serialXML.xml") Dim xmlWriter As New XmlSerializer(ds.GetType()) xmlWriter.Serialize(serialWriter, ds) serialWriter.Close() ds.Clear() End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class

Click here to download serialXML.xml

<?xml version="1.0" encoding="UTF-8"?>

<DataSet><xs:schema xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema" id="NewDataSet"><xs:element msdata:UseCurrentLocale="true" msdata:IsDataSet="true" name="NewDataSet"><xs:complexType><xs:choice maxOccurs="unbounded" minOccurs="0"><xs:element name="product"><xs:complexType><xs:sequence><xs:element type="xs:int" name="Product_ID" minOccurs="0"/><xs:element type="xs:string" name="Product_Name" minOccurs="0"/><xs:element type="xs:int" name="product_Price" minOccurs="0"/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xmldiffgram-v1"><NewDataSet><product diffgr:id="product1" diffgr:hasChanges="inserted" msdata:rowOrder="0"><Product_ID>1</Product_ID><Product_Name>product1</Product_Name><product_Price>9999</p roduct_Price></product><product diffgr:id="product2" diffgr:hasChanges="inserted" msdata:rowOrder="1"><Product_ID>2</Product_ID><Product_Name>product2</Product_Name><product_Price>2222</p roduct_Price></product><product diffgr:id="product3" diffgr:hasChanges="inserted" msdata:rowOrder="2"><Product_ID>3</Product_ID><Product_Name>product3</Product_Name><product_Price>3333</p roduct_Price></product><product diffgr:id="product4" diffgr:hasChanges="inserted" msdata:rowOrder="3"><Product_ID>4</Product_ID><Product_Name>product4</Product_Name><product_Price>4444</p roduct_Price></product></NewDataSet></diffgr:diffgram></DataSet>

How to de-serialize from an XML file to .Net Object


XML is a general purpose tag based language and very easy to transfer and store data across applications. XML Serialization is the process of serializing a .Net Object to the form of XML file or from an XML to .Net Object. During XML serialization, only the public properties and fields of an object are serialized. The following source code shows how to de-serialize the DataSet as it is streamed from an XML file back into memory.
Download Source Code Print Source Code

Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class

VB.NET DATAGRIDVIEW TUTORIALS

VB.NET DataGridView Tutorial


The following lessons teaches you the fundamental programming concepts of DataGridView control and its supporting classes, in detail. The DataGridView control provides a customizable table for displaying data. This control is designed to be a complete solution for displaying tabular data with Windows Forms. Also the DataGridView class allows us to customization of cells, rows, columns, and borders through the use of its properties You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. The cell is the fundamental unit of interaction for the DataGridView. All cells derive from the DataGridViewCell base class. Each cell within the DataGridView control can have its own style, such as text format, background color, foreground color, font etc.

The following lessons explain the basics of DataGridView control and steps through an example that builds simple vb.net programs. All the source code in the following examples ,we chose the Pubs database, which comes with SQL Server , as our target database.

VB.NET DataGridView binding - Sql Server


You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain. The following vb.net program shows how to bind a SQL Server dataset in a DataGridView. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class

DataGridView binding - OLEDB in VB.NET


The DataGridView can display data in Bound mode and unbound mode and Virtual mode. The easiest way to get started using the DataGridView control is to use it in basic data binding scenarios. The DataGridView control can display rows of data from a data

source. When you specify a data source for the DataGridView, by default it will construct columns for you automatically. This will be created based on the data types in the data source. The following vb.net program shows how to bind an OLEDB dataset in a DataGridView. Download Source Code Print Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Your .mdb path";" Dim sql As String = "SELECT * FROM Authors" Dim connection As New OleDbConnection(connectionString) Dim dataadapter As New OleDbDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class

DataGridView Sorting/Filtering in VB.NET


The DataGridView control provides a customizable table for displaying data. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. A DataView provides a means to filter and sort data within a DataTable. The following vb.net program shows how to filter and sort a DataGridView by using a DataView Object. Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv

Download Source Code

Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Titles" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Titles_table") connection.Close() Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv End Sub End Class

DataGridView adding rows and columns in VB.NET


The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms. The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The DataGridView control is used to display data from a variety of external data sources. Alternatively, you can add rows and columns to the control and manually populate it with data. The following vb.net source code shows how to manually create Columns and Rows in a DataGridView. DataGridView1.Columns(Index).Name = "Column Name" Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID"

DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) End Sub End Class

DataGridView hiding rows and columns in VB.NET


The DataGridView control provides a customizable table for displaying data. It gives you number of properties, methods and events to customize its appearance and behavior. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms . The following vb.net source code manually creates a DataGridView columns and rows and hide the second column and second row. DataGridView1.Rows(Index).Visible = False DataGridView1.Columns(Index).Visible = False Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row)

row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).Visible = False End Sub End Class

DataGridView ReadOnly rows and columns in VB.NET


The DataGridView control can display rows of data from a data source. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The ReadOnly property indicates whether the data displayed by the cell can be edited or not. You can set ReadOnly Property in three levels. You can make entire dataGridView as ReadOnly. dataGridView1.ReadOnly = true You can make entire row as ReadOnly dataGridView1.Rows(index).ReadOnly = true; You can make entire Column as ReadOnly dataGridView1.Columns(index).ReadOnly = true; The following vb.net source code shows how to make a row as Readonly in a DataGridView. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).ReadOnly = True End Sub End Class

Adding Button to DataGridView in VB.NET


The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. With the DataGridViewButtonColumn, you can display a column of cells that contain buttons.You can respond to user clicks in button cells by handling the DataGridView.CellClick event. The following vb.net program shows how to add a Button in Cell of a DataGridView control. Also it showing in the DataGridView.CellClick event which button the user clicked. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name"

DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim btn As New DataGridViewButtonColumn() DataGridView1.Columns.Add(btn) btn.HeaderText = "Click Data" btn.Text = "Click Here" btn.Name = "btn" btn.UseColumnTextForButtonValue = True End Sub Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick If e.ColumnIndex = 3 Then MsgBox(("Row : " + e.RowIndex.ToString & " Col : ") + e.ColumnIndex.ToString) End If End Sub End Class

Adding CheckBox to DataGridView in VB.NET


The DataGridView control uses several column types to display its information and enable users to modify or add information. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. The following vb.net program shows how to add a CheckBox in Cell of a DataGridView control and set the third row checkbox value as true. If you want to respond immediately when users click a check box cell, you can handle the CellClick event, but this event occurs before the cell value is updated. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim chk As New DataGridViewCheckBoxColumn() DataGridView1.Columns.Add(chk) chk.HeaderText = "Check Data" chk.Name = "chk" DataGridView1.Rows(2).Cells(3).Value = True End Sub End Class

Adding ComboBox to DataGridView in VB.NET


The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. You can populate the drop down list used for all cells the same way you would populate a ComboBox drop down list, either manually through the collection returned by the Items property, or by binding it to a data source through the DataSource, DisplayMember, and ValueMember properties. The following vb.net program shows how to add a ComboBox in Cell of a DataGridView control. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim cmb As New DataGridViewComboBoxColumn() cmb.HeaderText = "Select Data" cmb.Name = "cmb" cmb.MaxDropDownItems = 4 cmb.Items.Add("True") cmb.Items.Add("False") DataGridView1.Columns.Add(cmb) End Sub End Class

Adding Image to DataGridView in VB.NET


The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data. We can add an Image control in a column of DataGridView. This column type exposes Image and ImageLayout properties in addition to the usual base class properties. Setting the columns Image property results in that image being displayed by default for all the cells in that column. Populating an image column manually is useful when you want to provide the functionality of a DataGridViewButtonColumn, but with a customized appearance. The following vb.net program shows how to add a Image in column of a DataGridView control.

Download Source Code

Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim img As New DataGridViewImageColumn() Dim inImg As Image = Image.FromFile("Image Path") img.Image = inImg DataGridView1.Columns.Add(img) img.HeaderText = "Image" img.Name = "img" End Sub End Class

Adding ViewLink to DataGridView in VB.NET


The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. We can add hyperlink in the column of a DataGridView , the column type contains cells of type DataGridViewLinkCell and renders the text in the cell to look like a hyperlink. Link columns are not generated automatically when data binding a DataGridView control. To use link columns, you must create them manually and add them to the collection returned by the Columns property. The following vb.net program shows how to add a hyperlink in a column of DataGridView control.

Download Source Code

Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim lnk As New DataGridViewLinkColumn() DataGridView1.Columns.Add(lnk) lnk.HeaderText = "Link Data" lnk.Name = "http://vb.net-informations.com" lnk.Text = "http://vb.net-informations.com" lnk.UseColumnTextForLinkValue = True End Sub End Class

How to Paging in DataGridView

The DataGridView class allows customization of cells, rows, columns, and borders through the use of its properties . If a DataGridView has lot of rows then we can implement paging functionalities to the DataGridView control. While we implement paging we should know the boundaries of the pages to enable the paging in the DatagridView. The following vb.net program provides a way to programmatically implement paging in a Windows Datagrid View control. Here the DataGridView rows fixed as five rows and other two buttons are there for implementing paging functionalities. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Dim pagingAdapter As SqlDataAdapter Dim pagingDS As DataSet Dim scrollVal As Integer

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM authors" Dim connection As New SqlConnection(connectionString) pagingAdapter = New SqlDataAdapter(sql, connection) pagingDS = New DataSet() connection.Open() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") connection.Close() DataGridView1.DataSource = pagingDS DataGridView1.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click scrollVal = scrollVal - 5 If scrollVal <= 0 Then scrollVal = 0 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub End Class

How to Formatting in DataGridView

The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. Typically, however, multiple cells will share particular style characteristics. You can define appearance and formatting styles for individual cells, for cells in specific columns and rows, or for all cells in the control by setting the properties of the DataGridViewCellStyle objects accessed through various DataGridView control properties. The following vb.net program shows how to implement different ways of cell formatting in a DataGridView control. Download Source Code
Imports System.Data.SqlClient

Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" DataGridView1.GridColor = Color.Red DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None DataGridView1.BackgroundColor = Color.LightGray DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True] DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect DataGridView1.AllowUserToResizeColumns = False DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End Sub End Class

How to DataGridView Template

There are situations that you want greater control over the appearance of DataGridView rows than what is provided by the various DataGridView cell style properties. The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set any DataGridViewRow properties, including DefaultCellStyle. When displaying external data, however, the rows are generated automatically, but they are based on the row template, which you can set to an instance of your custom row type. The following vb.net code example illustrates how to use the row template to specify an initial row height and a minimum row height and BackColor. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

Button1.Click Dim row As DataGridViewRow = Me.DataGridView1.RowTemplate row.DefaultCellStyle.BackColor = Color.Bisque row.Height = 35 row.MinimumHeight = 20 Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class

How to DataGridView Printing

The DataGridView control provides a customizable table for displaying data. It gives you number of properties, methods and events to customize its appearance and behavior. Unfortunately the DataGridView doesn't have a built in printing functionality . So here we do a tricky way to print the content of DataGridView . Here we add a PrintDocument object to the project and handle the PrintPage event which is called every time a new page is to be printed. Here in the PrintPage event we create a Bitmap Object and draw the DataGridView to the Bitmap Object. In order to run this vb.net project you have to drag two buttons ,one for load data and one for print command, and drag a PrintDocument control on your form . The following picture shows how to drag PrintDocument Object to your project. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim bm As New Bitmap(Me.DataGridView1.Width, Me.DataGridView1.Height) DataGridView1.DrawToBitmap(bm, New Rectangle(0, 0, Me.DataGridView1.Width, Me.DataGridView1.Height)) e.Graphics.DrawImage(bm, 0, 0) End Sub End Class

How to Export datagridview to Excel


The DataGridView control provides a customizable table for displaying data. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The following vb.net source code shows how to Export the content of a datagridview to an Excel file.

Download Source Code

Print Source Code

Imports System.Data.SqlClient Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Int16, j As Int16 xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") For i = 0 To DataGridView1.RowCount - 2 For j = 0 To DataGridView1.ColumnCount - 1 xlWorkSheet.Cells(i + 1, j + 1) = DataGridView1(j, i).Value.ToString() Next Next

xlWorkBook.SaveAs("c:\vb.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _ Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue) xlWorkBook.Close(True, misValue, misValue) xlApp.Quit() releaseObject(xlWorkSheet) releaseObject(xlWorkBook) releaseObject(xlApp) MessageBox.Show("Over") End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing MessageBox.Show("Exception Occured while releasing object " + ex.ToString()) Finally GC.Collect() End Try End Sub End Class

How to Import data from Excel to DataGridView


The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data. You can use a DataGridView control to display data with or without an underlying data source. The following vb.net source code shows how to Import data from an Excel file to a DataGridView control . Download Source Code
Imports System.Data.SqlClient Public Class Form1

Print Source Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim MyConnection As System.Data.OleDb.OleDbConnection Dim DtSet As System.Data.DataSet Dim MyCommand As System.Data.OleDb.OleDbDataAdapter MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;") MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection) MyCommand.TableMappings.Add("Table", "Net-informations.com") DtSet = New System.Data.DataSet MyCommand.Fill(DtSet) DataGridView1.DataSource = DtSet.Tables(0) MyConnection.Close() End Sub End Class

Database operations in DatagridView

The DataGridView control can display rows of data from a data source. The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain. The following vb.net source code illustrate how to connect a DataGridView to a database and addnew/update or delete the database values from DataGridView. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Dim sCommand As SqlCommand

Print Source Code

Dim Dim Dim Dim

sAdapter As SqlDataAdapter sBuilder As SqlCommandBuilder sDs As DataSet sTable As DataTable

Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Stores" Dim connection As New SqlConnection(connectionString) connection.Open() sCommand = New SqlCommand(sql, connection) sAdapter = New SqlDataAdapter(sCommand) sBuilder = New SqlCommandBuilder(sAdapter) sDs = New DataSet() sAdapter.Fill(sDs, "Stores") sTable = sDs.Tables("Stores") connection.Close() DataGridView1.DataSource = sDs.Tables("Stores") DataGridView1.ReadOnly = True save_btn.Enabled = False DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect End Sub Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click DataGridView1.[ReadOnly] = False save_btn.Enabled = True new_btn.Enabled = False delete_btn.Enabled = False End Sub Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index) sAdapter.Update(sTable) End If End Sub

Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click sAdapter.Update(sTable) DataGridView1.[ReadOnly] = True save_btn.Enabled = False new_btn.Enabled = True delete_btn.Enabled = True End Sub End Class

You might also like