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 .

If the Option Explicit mode is OFF . Vb.. it will generate a compile-time error whenever a variable that has not been declared is encountered . _ ByVal e As System..Object. you can reduce the possible errors that result from misspelled variable names.Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. By default the Option Explicit is On With the Option Explicit On . you have to declare all the variable before you use it in the program . On and Off mode. VB. . an exception happen and it will go to catch block and then it will go to finally block.EventArgs) Handles Button1.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.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 ." first and then "Finally block executed " . If Option Explicit mode in ON . Because in Option Explicit On mode you have to declare each variable in the program for storing data. That is when you execute this code . If not .Net automatically create a variable whenever it sees a variable without proper declaration.") Finally MsgBox("Finally block executed ") End Try End Sub End Class When you execute this program you will "Exception catch here . Option Explicit [On Off] The Option Explicit has two modes.

Object. so the default mode of Option Explicit On is using. _ ByVal e As System.Click someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class Here "someVariable" is not declared .Object. because the Option Explicit Of . Take a look at the following program . without any compiler error you can continue the program VB. _ ByVal e As System. . declare a String variable and assigned a value in it and it displays.NET Option Strict [On | Off] Option Strict is prevents program from automatic variable conversions. so we do not need to put it in the source code. The following program is a normal vb. The default is Option Explicit On .NET Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Click Dim someVariable As String someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class The above 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.net program .Take a look at the following programs. that is implicit data type conversions . it will give you a clear picture of Option Explicit.EventArgs) Handles Button1.EventArgs) Handles Button1. VB.

Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum .EventArgs) Handles Button1.net program and is in default Option Strict Off .Object.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.Option Strict [On Off] By default Option Strict is Off From the following example you can understand the use of Option Strict.Object. _ ByVal e As System. Take a look at the following program. Because its Option Strict Off we can convert the value of Long to an Integer. VB.NET Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. _ ByVal e As System. Download Source Code Print Source Code Option Strict On Public Class Form1 Private Sub Button1_Click(ByVal sender As System.

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

EventArgs) Handles Button1. _ ByVal e As System. Operating System Information The following VB. The OperatingSystem Class provides a method to copy an instance of OperatingSystem. If you need a type to contain other information about an operating system.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. create your own type. The OperatingSystem class is not a general purpose class and you cannot derive a more inclusive type from the OperatingSystem class.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" . or methods you require. and a method to return a string representation of operating system information. . then include a field of type OperatingSystem and any additional fields.Object. Because the On Error statement redirect the exception to the Label statement. properties.NET program retrieves the current operating system information like version and platform identifier with the help of OperatingSystem Class and Environment Class.

ByVal e As System.ToString) End Sub End Class Operating System Information The following VB.Object. Dim _os As OperatingSystem _os = Environment.VersionString. .OSVersion MsgBox(_os.EventArgs) Handles Button1. and means to manipulate. properties. create your own type. or methods you require.The Environment Class provides information about. The OperatingSystem Class provides a method to copy an instance of OperatingSystem. The Environment Class has a property called OSVersion which returns an object of type OperatingSystem. If you need a type to contain other information about an operating system. 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. the current environment and platform. then include a field of type OperatingSystem and any additional fields.Click Dim _os As OperatingSystem _os = Environment.OSVersion Download Source Code Public Class Form1 Print Source Code Private Sub Button1_Click(ByVal sender As System.NET program retrieves the current operating system information like version and platform identifier with the help of OperatingSystem Class and Environment Class.

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 . the current environment and platform. and means to manipulate. The Environment Class has a property called OSVersion which returns an object of type OperatingSystem. Dim _os As OperatingSystem _os = Environment.Click Dim _os As OperatingSystem _os = Environment.. and making decision based on that contition.END WHILE etc.OSVersion Download Source Code Public Class Form1 Print Source Code Private Sub Button1_Click(ByVal sender As System.VersionString. is use for examining the conditions that we provided. How to use IF ELSE in VB. While.NET The conditional statement IF ELSE .OSVersion MsgBox(_os.NET PROGRAM FLOW CONTROLS TUTORIALS VB.EventArgs) Handles Button1. The conditional statement examining the data using comparison operators as well as logical operators. .Object.The Environment Class provides information about.ToString) End Sub End Class VB. ByVal e As System..

If you want o check more than one condition at the same time . that is the program will execute the code between IF and ELSE statements. that is the program will execute the code between ELSE and END IF statements. 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 . If the contition is FLASE then the control goes to between ELSE and END IF block . you can use ElseIf . 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 .When we want to analyze a mark lists we have to apply some conditions for grading students depends on the marks.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 .

6. 2. 5. 3. 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 . 8. 1."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. 9."Got First Class " Line 5 : Checking the total marks greaterthan or equal to 40 Line 6 : If total marks greater than 40 show message . if the marks less than 40 then the student fail.4) The last condition is ."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 .NET Source Code .NET program. 7. 4. Now here implementing these conditions in a VB.

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.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 . ByVal e As System. 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 .Object.EventArgs) Handles Button1.

FOR NEXT Loop : The FOR NEXT Loop . ByVal e As System. FOR NEXT Loop. starValue : The starting value assign to counter variable .EventArgs) Handles Button1. endValue : When the counter variable reach end value the Loop will stop . in these situations you can use loop statements to achieve your desired results.NET 2005 ( VB.. FOR EACH Loop .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.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.Public Class Form1 Private Sub Button1_Click(ByVal sender As System. .Object. For var=[startValue] To [endValue] [Step] [loopBody] Next [var] var : The counter for the loop to repeat the steps. execute the loop body (the source code within For .Next code block) to a fixed number of times.NET 2005) . WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.

NET Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. 1.EventArgs) Handles Button1. 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 you want to show a messagebox 5 times and each time you want to see how many times the message box shows. ByVal e As System.Object. 3.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 .loopBody : The source code between loop body Lets take a simple real time example . 4. if the counter not reach the endVal VB. 2. 5.

How to use FOR EACH loop in VB.NET .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 .NET provides a keyword Exit to use within the loop body.EventArgs) Handles Button1.Object. the program shows the message box only three times . If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic. ByVal e As System.End Class When you execute this program . 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. It will show messagebox five time and each time it shows the counter value.

NET 2005) .COM" .COM" 2. 1. MsgBox(singleChar) 4. FOR NEXT Loop. in these type of situation you can use For Each loop. siteName = "HTTP://NET-INFORMATIONS. Next Line 1: Assigning the site name in a variable . 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 .NET 2005 ( VB.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. WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic. in these situations you can use loop statements to achieve your desired results. every character in a String ) . or every single files in a folder or . FOR EACH Loop . 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. For Each singleChar In siteName 3. if you want to display the each character in the website name "HTTP://NET-INFORMATIONS. it is convenient to use For Each Loop.

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.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. End While Loop execute the code body (the source code within While and End while statements ) until it meets the specified condition. in these situations you can use loop statements to achieve your desired results.End While While . WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic. .Object.Click Dim siteName As String Dim singleChar As Char siteName = "HTTP://NET-INFORMATIONS.EventArgs) Handles Button1. FOR NEXT Loop.NET 2005) . FOR EACH Loop . ByVal e As System. While .NET 2005 ( VB. How to use vb..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..

EventArgs) Handles Button1. Message 4.Object.While [condition] [loop body] End While Condition : The condition set by the user 1. 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. ByVal e As System. counter = counter + 1 5. While (counter <= 10) 3.Click Dim counter As Integer counter = 1 While (counter <= 10) MsgBox("Counter Now is : " counter) counter = counter + 1 End While End Sub . counter = 1 2.

or an attempted illegal cast. Custom Exceptions in VB.NET Visual Basic .. Exceptions are objects that encapsulate an irregular circumstance. Download Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. ByVal e As System. In VB. End While loop.Click Try Dim i As Integer Print Source Code .Object. which is available in previous versions of Microsoft Visual Basic. You can also throw an exception from within your own code using the keyword Throw.NET program shows.NET offers structured exception handling that provides a powerful.End Class When you execute the program 10 times the message shows with counter and exit from the While .EventArgs) Handles Button1. a file that cannot be opened. such as when an application is out of memory. Try your code block Catch ex As Exception exception handling block Finally final cleanup block End Try The following 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. more readable alternative to "On Error Goto" error handling. how to create a custom exception class and how it is using in the program.

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. A dimension is a direction in which you can vary the specification of an arrays elements.ApplicationException Public Sub New(ByVal message As String) MyBase. called an index or subscript. Dim offices(40. Some arrays have two dimensions. The individual values are called the elements of the array. to tell them apart. such an array uses two indexes. Dim values() As Double An array that uses more than one index or subscript is called multidimensional. therefore.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. for buildings 0 through 40 and floors 0 through 5. 5) As Byte . The following example declares a variable to hold a twodimensional array of office counts.

net (vb.NET Collections Visual Basic .NET program shows a simple example of how to insert values in a two dimensional array and retrieve the values from two dimensional array.Object.NET Collections are data structures that holds data in different ways for flexible operations .net) programs. 1) = "Fourth (1.1)" For i = 0 To strArr. j As Integer Dim strArr(1. How to VB. 1) = "Second (0. In the following chapters you can see how to manage these datastructures in your visual basic. 0) = "First (0. 2) As String strArr(0.The following VB.EventArgs) Handles Button1. The important datastructres in the Colletions are ArrayList . HashTable .0)" strArr(0.0)" strArr(1. Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. 0) = "Third (1.1)" strArr(1.NET CONNECTIONS VB. ByVal e As System.Click Dim i.GetUpperBound(0) MsgBox(strArr(i.GetUpperBound(0) For j = 0 To strArr. Stack and Queue etc.NET ArrayList . j)) Next Next End Sub End Class VB.

item) index : The position of the item in an ArrayList Item : The Item to be add the ArrayList . to do with ArrayList.add(Item) Item : The Item to be add the ArrayList Dim ItemList As New ArrayList() ItemList. 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.. ArrayList contains a simple list of values and very easily we can add .NET Collections. that is it grow dynamically and also shrink . view etc. It is very flexible becuse we can add without any size information . delete .Add("Item4") How to Insert an Item in an ArrayList ? Syntax : ArrayList.ArrayList is one of the most flixible data structure from VB. insert .insert(index.

Add("Item1") ItemList.Add("Item4") ItemList.EventArgs) Handles Button1.RemoveAt(2) How to sort ArrayList ? Syntax : ArrayListSort() The following VB.Remove("item2") How to remove an item in a specified position from an ArrayList ? Syntax : ArrayList.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. "item6") How to remove an item from arrayList ? Syntax : ArrayList.Click Dim i As Integer Dim ItemList As New ArrayList() ItemList.Insert(3. ByVal e As System.Add("Item5") ItemList.Remove(item) Item : The Item to be add the ArrayList ItemList.Object.RemoveAt(index) index : the position of an item to remove from an ArrayList ItemList.Add("Item2") ItemList.Add("Item3") .ItemList.

Item(i)) Next End Sub End Class 1 index ArrayList") 1 When you execute this program .Sort() 'remove an item ItemList. "Item6") 'sort itemms in an arraylist ItemList. How to VB.MsgBox("Shows Added Items") For i = 0 To ItemList. Next it remove the item1 and also remove the item in the third position . The common functions using in Hashtable are : Add : To add a pair of value in HashTable Syntax : HashTable. at first add five items in the arraylist and displays.Remove("Item1") 'remove item from a specified ItemList.RemoveAt(3) MsgBox("Shows final Items the For i = 0 To ItemList.Insert(3.Add(Key.Count MsgBox(ItemList. Both key and value are Objects.Count MsgBox(ItemList. and then sort all items.Value) Key : The Key value .Net HashTable HashTable stores a Key Value pair type collection of data . Finally it shows the existing items. Then again one more item inserted in the third position . We can retrive items from hashTable to provide the key .Item(i)) Next 'insert an item ItemList.

Add("4". "Tue") weeks.Add("1". "Fri") weeks.Add("5".ContainsKey(key) Key : The Key value for search in HahTable ContainsValue : Check the specified Value exist in HashTable Synatx : HashTable. "Mon") weeks.Add("7". ByVal e As System.Add("2".Add("6".Click Dim weeks As New Hashtable Dim day As DictionaryEntry weeks.Object.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. "Thu") weeks.Add("3". "Wed") weeks.Value : The value of corrosponding key ContainsKey : Check if a specified key exist or not Synatx : HashTable. "Sat") . "Sun") weeks.EventArgs) Handles Button1.

Commonly used methods : Push : Add (Push) an item in the stack datastructure Syntax : Stack. Stack follows the push-pop operations.NET Collections .'Display a single Item MsgBox(weeks.Push(Object) Object : The item to be inserted. Finaly it displays all item exist in the HashTable.Item("5")) 'Search an Item If weeks.Remove("3") 'Display all key value pairs For Each day In weeks MsgBox(day. How to VB." day. Then it check the item "Tue" is existing or not . .ContainsValue("Tue") Then MsgBox("Find") Else MsgBox("Not find") End If 'remove an Item weeks. That is we can push the items into a stack and get it in reverse order. Next it remove the third item from HashTable.Net Stack Stack is one of another easy to use VB. Stack returns the last item first.Value) Next End Sub End Class When you execute this program it add seven weekdays in the hashtable and display the item 5.Key " -. that is we can Push Items into Stack and Pop it later also it follows the Last In First Out (LIFO) system.

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

The default number of array elements is set to zero and the reference element is set to null.IO.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 . to tell them apart.Object.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.FileStream oFileStream = New System. The elements of an array can be of any type. Arrays helps us create shorter and simpler code in many situations. System. Dim months(11) As String An array allows you to refer to these related values by the same name and to use a number.Write(byteData.txt".Length) oFileStream. 0.Dim str As String = "http://vb.Text. byteData.EventArgs) Handles Button1.FileStream("c:\bytes.GetBytes(str) Dim oFileStream As System.FileMode.net-informations.com" Dim encod As New System. including an array type.IO.IO.Create) oFileStream. ByVal e As System.UTF8Encoding Dim byteData() As Byte = encod.NET source code shows how to write the array content into a text file. called an index or subscript.NET inherit from the Array class in the System namespace. The following VB. Download Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Arrays in VB.

The following sections describes . how to work with VB.NET String. you create a new String Object .NET STRING CLASS The String Class represents character strings.WriteAllLines("c:\file. The String class is a sealed class . How to VB.Text.String. The String object is Immutable .StringBuilder class to modify a string without creating a new object.Length() As Integer Returns: Integer : The number of characters in the specified String . The String type represents a string of Unicode Characters . it cannot be modified once it created. months) End Sub End Class VB.IO. System. System.Length() The Length() function in String Class returned the number of characters occurred in a String. The String data type comes from the System. So if you are in a situation in continuous operation with String Object it is recommended to use System.String class . In the following sections you can see the important methods in details with descriptions .txt".StringBuilder . that means every time you use any operation in the String object .NET String class .Text.NET STRING TUTORIALS VB. so you cannot inherit another class from the String class.File.months(6) = "Jul" months(7) = "Aug" months(8) = "Sep" months(9) = "Oct" months(10) = "Nov" months(11) = "Dec" System.

Length()) End Sub End Class When you execute this source code you will get 17 in the messagebox. Exceptions: . Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.The string to be inserted.The index of the specified string to be inserted.Click Dim str As String str = "This is a Test" MsgBox(str. Returns: String . How to VB.Insert(Integer ind. System. String str) as String Parameters: ind . _ ByVal e As System.Object.Length() returns 14.EventArgs) Handles Button1.For ex: "This is a Test".String.Insert() The Insert() function in String Class will insert a String in a specified index in the String instance.NET String. str .The result string.

For ex: "This is Test".Object.NET Test" Dim insStr As String = "Insert " Dim strRes As String = str.NET Insert Test" How to VB. _ ByVal e As System.The parameter string to check its occurrences Returns: .EventArgs) Handles Button1.NET String.String.Insert(8.System."Insert ") returns "This is Insert Test" Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this instance System.IndexOf(String str) As Integer Parameters: str .Insert(15.Click Dim str As String = "This is VB. insStr) MsgBox(strRes) End Sub End Class When you execute this program you will get the message box showing "This is VB. System.ArgumentNullException : If the argument is null.IndexOf() The IndexOf method in String Class returns the index of the first occurrence of the specified substring.

Object.EventArgs) Handles Button1.Integer .Format() VB.IndexOf("Test") returns 10 "This is a test". .If the parameter String occurred as a substring in the specified String it returns position of the first character of the substring .Click Dim str As String str = "VB.NET TOP 10 BOOKS" MsgBox(str.NET String Format method replace the argument Object into a text equivalent System. If it does not occur as a substring. Exceptions: System. How to VB.IndexOf("vb") returns -1 Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. For ex: "This is a test". _ ByVal e As System.Striing. That means the substring "BOOKS" occurred and start in the position 14.ArgumentNullException: If the Argument is null.NET String.IndexOf("BOOKS")) End Sub End Class When you execute this program you will get the number 14 in the message box. -1 is returned.

Returns: String : The formatted String Exceptions: System.Format("Today's date is {0:D}". The number indicating an argument to format is less than zero. 10) will return $10. or greater than or equal to the number of specified objects to format. For ex : Currency : String.System.ArgumentNullException : The format String is null. 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.Format(ByVal format As String.00 The currency symbol ($) displayed depends on the global locale settings.Now) . System. Date : String. DateTime.FormatException : The format item in format is invalid.Format("{0:c}".

Equals() VB. _ ByVal e As System.Click Dim dNum As Double dNum = 32.String.NET String Equals function is to check the specified two String Object values are same or not System. dNum)) End Sub End Class When you run this source code yo will get "Formated String 32.Equals(String str1.Object.EventArgs) Handles Button1.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.123456789 MsgBox("Formated String " & String.1234" How to VB.NET String.Format("{0:n4}". String str2) As Boolean Parameters: String str1 : The String argument String str2 : The String argument Returns: .Format("The current time is {0:T}".You will get Today's date like : 01 January 2005 Time : String. DateTime.

ToLower.EventArgs) Handles Button1.Click Dim str1 As String = "Equals" Dim str2 As String = "Equals" If String.CopyTo() .NET String.Boolean : Yes/No It return the values of the two String Objects are same For ex : Str1 = "Equals()" Str2 = "Equals()" String.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.Str2) returns True String.Equals(Str1.Equals(Str1.Equals(str1. _ ByVal e As System.Object. 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.

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. ByVal destinationIndex As Integer. 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.ArgumentOutOfRangeException : Source Index.ArgumentNullException : If the destination is null System.Click Dim str1 As String = "CopyTo() sample" Dim chrs(5) As Char .String. _ ByVal e As System.VB.EventArgs) Handles Button1. System.CopyTo(ByVal sourceIndex As Integer.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. ByVal destination() As Char.Object.

chrs. _ ByVal e As System.EventArgs) Handles Button1.NET String Copy method is create a new String object with the same content System.str1.ArgumentNullException : If the argument is null.Copy() VB.CopyTo(0.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. 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.String. Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.NET Copy() test" str2 = String.Copy(str1) .Object.Click Dim str1 As String Dim str2 As String str1 = "VB.

Contains("is") return True "This is a Test".ArgumentNullException : If the argument is null .String.NET String Class check the specified parameter String exist in the String System.NET String.Contains(String str) As Boolean Parameters: String str .MsgBox(str2) End Sub End Class When you run this source code you will get same content of str1 in str2 How to VB.Contains() The Contains method in the VB.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".input String for search Returns: Boolean .Contains("yes") return False Exceptions: System.

String.String str2. System.Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System. _ ByVal e As System.Compare(String str1.Click Dim str As String str = "VB.EventArgs) Handles Button1.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. 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: .Compare() The VB.NET String Compare function is use to compare two String Objects.Object.NET TOP 10 BOOKS" If str.NET String.

Click Dim str1 As String Dim str2 As String str1 = "vb.Object.net" str2 = "VB.Compare(str1. Public Function Clone() As Object . str2.NET String Clone() method returns a reference to this instance of String.EventArgs) Handles Button1.NET String. zero or greater than zero.NET" Dim result As Integer result = String. 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.Integer : returns less than zero.Compare(str1.Clone() The VB. 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. _ ByVal e As System. str2) MsgBox(result) result = String.

NET String.Object.Object.EventArgs) Handles Button1.Click Dim str As String = "Clone() Test" Dim clonedString As String clonedString = str.Clone() The VB.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.Clone() .Click Dim str As String = "Clone() Test" Dim clonedString As String clonedString = str.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. _ ByVal e As System.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. _ ByVal e As System.EventArgs) Handles Button1.

ArgumentOutOfRangeException : the beginIndex or length less than zero.Object.substring() Substring in Vb. The substring begins at the specified given index and extended up to the given length.Click . Returns: The specified substring. Exceptions: System.EventArgs) Handles Button1.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. Public Function Substring(ByVal startIndex As Integer. 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. length: The number of characters in the substring. ByVal length As Integer) As String Parameters: startIndex: The index of the start of the substring.NET String.Net String Class returns a new string that is a substring of this string. _ ByVal e As System.

Object.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.Click Dim str As String Dim strArr() As String Dim count As Integer str = "vb. 9) MsgBox(retString) End Sub End Class When you execute this program .Dim str As String Dim retString As String str = "This is substring test" retString = str.NET String.Char array.Split(" ") . How to VB.EventArgs) Handles Button1.Substring(8.net split test" strArr = str. Public Function Split(ByVal ParamArray separator() As Char) As String() Parameters: separator .Split() Vb. its will display "subtring" in the messagebox.Net String Split function returns an array of String containing the substrings delimited by the given System. _ ByVal e As System.

NET String Class check if the Parameter String EndsWith the Specified String System. How to VB.net" "split" "test" in separate messagebox.EndsWith() EndsWith in VB.String.EndsWith("is") returns False Exceptions: .For count = 0 To strArr.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". you will get "vb.The passing String for it EndsWith Returns: Boolean .EndsWith("Test") returns True "This is a Test".Length .NET String.EndsWith(String suffix) as Boolean Parameters: suffix .1 MsgBox(strArr(count)) Next End Sub End Class When you execute this programme .

NET TOP 10 BOOKS" If str.EventArgs) Handles Button1.Click Dim str As String str = "VB.Object.Concat(ByVal str1 As String.ArgumentNullException : If the argument is null Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.System.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.Concat() Concat in VB.NET String. ByVal e As System.String.NET String Class using for concat two specified String Object System. ByVal str2 As String) As String String Concat method returns a new String Parameters: String str1 : Parameter String String str2 : Parameter String .

Click Dim str1 As String Dim str2 As String str1 = "Concat() " str2 = "Test" MsgBox(String.Globalization. For example. _ ByVal e As System. sublanguage. and cultural conventions.CultureInfo("en-US") The String class indirectly uses this class to obtain information about the default culture.CultureInfo A neutral culture is specified by only the two-letter lowercase language code.Concat(str1. The CultureInfo class renders culture-specific information.Object. . such as the associated language. str2)) End Sub End Class When you run this source code you will get "Concat() Test " in message box. Dim cultureInfo As New System.Globalization.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.EventArgs) Handles Button1. The follwoing VB. country/region. System.NET source code shows how to convert a string to Title Case. How to String Title Case Title Case converts the first character of a word to uppercase and the rest of the characters to lowercase. and "de" specifies the neutral culture for German. calendar. "fr" specifies the neutral culture for French.

Dim message As String Dim stringReader As New StringReader(String) The next line from the underlying string. StringReader. Dim stringWriter As New StringWriter() stringWriter. The following program shows how to use StringWriter and StringReader Classes in VB. StringBuilder Class Represents a mutable string of characters and this class cannot be inherited.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. or Nothing if the end of the underlying string is reached.EventArgs) Handles Button1.ReadLine Method Reads a line from the underlying string.net-informations.NET.WriteLine("vb.Object. .Download Source Code Public Class Form1 Print Source Code Private Sub Button1_Click(ByVal sender As System.TextInfo.com") StringReader Class Implements a TextReader that reads from a string. WriteLine(String) method writes a string followed by a line terminator to the text stream.Click Dim _str As String Dim cultureInfo As New System.CultureInfo("en-US") _str = cultureInfo. ByVal e As System.Globalization.

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

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

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

Select Report type from Crystal Reports gallery. .

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

Select Microsoft OLE DB Provider for SQL Server . .

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

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

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

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

Select Form's source code view and put the code on top Imports CrystalDecisions.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object.Engine Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions.Click .EventArgs) Handles Button1. ByVal e As System.CrystalReports.CrystalReports.

rpt") The Crystal Reports is in your project location.rpt") CrystalReportViewer1.rpt .Refresh() End Sub End Class NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. . After you run the source code you will get the report like this. there you can see CrystalReport1.Dim cryRpt As New ReportDocument cryRpt. So give the full path name of report here.ReportSource = cryRpt CrystalReportViewer1.

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

Create a DataBase "crystaldb" In the crystaldb database . OrderDetails . 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 . create three tables OrderMaster . Product .

[OrderMaster_date] [datetime] NULL . [OrderMaster_customername] [varchar] (50).The following picture shows the relations of each table : SQL command for creation tables are follows : CREATE TABLE [dbo]. [OrderMaster_createduser] [varchar] (50) ) ON [PRIMARY] .[OrderMaster] ( [OrderMaster_id] [int] NOT NULL .

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

Order Details Table Data Product Table Data .

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

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

Next step is to select the appropriate connection to your database.Accept the default settings and click OK. 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 . enter userid . Then you will get your Server name under OLEDB Connection from there select database name (Crystaldb) and click the tables . and click finish. password and select your Database Name . . Then the screen shows OLE DB Property values . Select your Sql Server name . Click next . leave it as it is . then you can see all your tables from your database.

The next step is to make relation between these selected tables. because we are creating report from three tables ( OrderMaster. OrderDetails. Product) . 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.Select all table from the table list to right side list box. . After made the relation the screen is look like the following picture .

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

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

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

EventArgs) Handles Button1.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.CrystalReports.CrystalReports.Click .Engine Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions.Select Form's source code view and put the code on top Imports CrystalDecisions. ByVal e As System.Object.

rpt") The Crystal Report is in your project location. So give the full path name of report here.Dim cryRpt As New ReportDocument cryRpt.rpt") CrystalReportViewer1. there you can see CrystalReport1.rpt .ReportSource = cryRpt CrystalReportViewer1.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. After you run the source code you will get the report like this. .Refresh() End Sub End Class NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.

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

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

Select Parameter Field from Field Explorer and right Click. Fill the appropriate name for Name and Promting text fields .

. Right click on Crystal Reports designer window .After creating the parameter field . Form the following picture you can understand the selection fields. First you have to select OrderMaster. Double click each field then it will be selected. This for entering the selection formula. select REPORT -> SELECTION FORMULA -> RECORD . For creating selection formula .OrderMaster_customername from Report Field and select the comparison operator and select the parameter field. Then you can see the record Selection Formula Editor. we have to create the selection formula for the Crystal Reports . For that you have to select the fields from above fields and make the formula .

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

CrystalReports.Shared Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions.Object.EventArgs) Handles Button1.rpt") . _ ByVal e As System.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Select Form's source code view and import the following : Imports CrystalDecisions.Click Dim cryRpt As New ReportDocument cryRpt.Engine Imports CrystalDecisions.Engine Imports CrystalDecisions.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.CrystalReports.

Now you can run the program .Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.Item("Customername") crParameterValues = crParameterFieldDefinition. So give the full path name of report here. . there you can see CrystalReport1.Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue crParameterDiscreteValue.ReportSource = cryRpt CrystalReportViewer1.CurrentValues crParameterValues.Clear() crParameterValues.Text crParameterFieldDefinitions = cryRpt.Refresh() End Sub End Class NOTES: cryRpt.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.Value = TextBox1.rpt .ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.rpt") The Crystal Report is in your project location. Enter a Customer Name(enter any existing customer from Ordermaster table) and click the button .Add(crParameterDiscreteValue) crParameterFieldDefinition. then your report is look like the following picture.DataDefinition.

Click here to see Database Structure .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 . In this tutorial we are passing an Integer Parameter to Crystal Reports from VB.Here we get the result of the Customer4's order details. . VB.NET.

Then we will get the following screen and fill the fields like in the picture .NET and get the result. we have to create the selection formula for the Crystal Reports . .NET. After creating the parameter field . For creating selection formula . This is very similar to that tutorial . we saw passing a string parameter to Crystal Reports from VB. Then you can see the record Selection Formula Editor. So please take a look at the complete part of passing a string parameter to Crystal Reports from VB. we have to create a new Integer parameter in the Parameter Fields of Field Explorer. Right click on Crystal Reports designer window . For that you have to select the fields from above lists and make the formula . select REPORT -> SELECTION FORMULA -> RECORD . When we pass an Integer parameter . so here showing only the change information part only.In the previous tutorial . This for entering the selection formula.

button and CrystalReportViewer control to your form.Here we made the formula like select the records from Product table whose value is greater than the input value. Now the designing part is over and the next step is to call the created Crystal Reports in VB.vb) you created in VB. Select Form's source code view and import the following : .NET through Crystal Reports Viewer control . Double click each field then it will automatically selected After the creation of selection formula close that screen . Select the default form (Form1. 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.NET and drag a Textbox .

Item("Price") crParameterValues = crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.CrystalReports.ToInt32(TextBox1.CurrentValues crParameterValues.Engine Imports CrystalDecisions.Text) crParameterFieldDefinitions = _ cryRpt.ReportSource = cryRpt CrystalReportViewer1.DataDefinition. _ ByVal e As System.Add(crParameterDiscreteValue) crParameterFieldDefinition.CrystalReports.Click Dim cryRpt As New ReportDocument cryRpt.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Shared Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions.Object.Value = Convert.Imports CrystalDecisions.Engine Imports CrystalDecisions.Refresh() End Sub End Class NOTES: .Clear() crParameterValues.rpt") Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue crParameterDiscreteValue.EventArgs) Handles Button1.

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

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

This for entering the selection formula.NET and drag a Textbox .orderdate . 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.Then you can see the record Selection Formula Editor. Here we are making the formula like . button and CrystalReportViewer control to your form. For that you have to select the fields from above lists and make the formula . .vb) you created in VB. 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. Select the default form (Form1.NET through Crystal Report Viewer control .

EventArgs) Handles Button1.CrystalReports.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Value = TextBox1.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object.Select Form's source code view and import the following : Imports CrystalDecisions.DataDefinition.Add(crParameterDiscreteValue) crParameterFieldDefinition.Item("Orderdate") crParameterValues = crParameterFieldDefinition.Clear() crParameterValues.Engine Imports CrystalDecisions.Click Dim cryRpt As New ReportDocument cryRpt.CurrentValues crParameterValues. _ ByVal e As System.Refresh() End Sub End Class .ReportSource = cryRpt CrystalReportViewer1.rpt") Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue crParameterDiscreteValue.Text crParameterFieldDefinitions = _ cryRpt.Shared Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.

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

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

Password = "YOUR DATABASE PASSWORD" End With CrTables = cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. "YOUR DATABASE NAME" . So give the full path name of report here.EventArgs) Handles Button1.rpt") The Crystal Report is in your project location.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.rpt") With crConnectionInfo .Tables For Each CrTable In CrTables crtableLogoninfo = CrTable.rpt .DatabaseName = "YOUR DATABASE NAME" . there you can see CrystalReport1.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.Object.Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Refresh() End Sub End Class NOTES: cryRpt. _ ByVal e As System.LogOnInfo crtableLogoninfo. "YOUR DATABASE PASSWORD" with your correct values . You have to replace the source code values of "YOUR SERVER NAME" . .ApplyLogOnInfo(crtableLogoninfo) Next CrystalReportViewer1.Database.ConnectionInfo = crConnectionInfo CrTable.ReportSource = cryRpt CrystalReportViewer1.ServerName = "YOUR SERVER NAME" . "YOUR DATABASE USERNAME" .UserID = "YOUR DATABASE USERNAME" .

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

Before starting this tutorial. here we need one more field Prodcut->Price . Then you will get an Input Message Box . Right Click Formula Field in the Field Explorer and click New. that means each in each row we are showing the total of qty and price. Order Date .If you have a Crystal Reports with Qty and Price . If you do not know how to create this report . you need an additional field in your Crystal Reports for the Total of QTY X PRICE . Product Name and Product Price . In that report selecting only four fields . just look the previous tutorial Crystal Report from multiple tables . In this tutorial we are showing the all orders with qty and price and the total of each row . Create a new Crystal Reports with fields CustomerName . 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 . type Total in textbox and click Use Editor . In this situation you have to use the Formula Field in Crystal Reports.

Now you can see Total Under the Formula Field .Now you can see Formula Editor screen . Double click each field for selection. . For that we select OrderDetails.Price . Here we want the result of Qty X Price . Drag the field in to the Crystal Reports where ever you want .Qty . the multiplication operator and Product. Now you can enter which formula you want .

vb) you created in VB. _ ByVal e As System.Object.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub .rpt") CrystalReportViewer1.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.Now the designing part is over . Select Form's source code view and import the following : Imports CrystalDecisions.Click Dim cryRpt As New ReportDocument cryRpt.NET and drag a button and CrystalReportViewer control to your form.EventArgs) Handles Button1.Engine Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.CrystalReports. Select the default form (Form1.

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

Click Ok button . just below the Total field and select Insert -> Summary .All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) .Click here to see Database Structure . take a look at the previous tutorial Crystal Report Formula Field. Here we are taking the grand total of the Total field . 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 . and summary location Grand Total (Report Footer) . select the Total from the combo box and Sum from next Combo Box . In the Crystal Reports designer view right click on the Report Footer . The Total field is a Formula field is the result of qty X price . So before we start this tutorial . Then you will get a screen . Please take a look at the database structure before you start this tutorial .

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

Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.vb) you created in VB. Select Form's source code view and import the following : Imports CrystalDecisions.Engine Put the following source code in the button click event Download Source Code Print Source Code Imports CrystalDecisions. .Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.rpt") CrystalReportViewer1.rpt") The Crystal Report is in your project location.rpt . When you run this program you will get the following screen.ReportSource = cryRpt CrystalReportViewer1.NET and drag a button and CrystalReportViewer control to your form. _ ByVal e As System.EventArgs) Handles Button1.CrystalReports.Refresh() End Sub End Class NOTES: cryRpt. So give the full path name of report here.Object.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. Select the default form (Form1. there you can see CrystalReport1.Now the designing part is over .Engine Imports CrystalDecisions.CrystalReports.

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

EventArgs) Handles Button2.ExportFormatType = ExportFormatType.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions() CrDiskFileDestinationOptions.DiskFile .NET Crystal Reports Export to Excel .FormatOptions = CrFormatTypeOptions End With cryRpt.Object.DestinationOptions = CrDiskFileDestinationOptions .pdf) in your computer's C: VB. _ ByVal e As System.ExportOptions With CrExportOptions .Export() Catch ex As Exception MsgBox(ex.PortableDocFormat .ExportDestinationType = ExportDestinationType.rpt") The Crystal Report is in your project location. When you run this program you will get the PDF file (crystalExport.rpt . So give the full path name of report here.Private Sub Button2_Click(ByVal sender As System.ToString) End Try End Sub End Class NOTES: cryRpt.pdf" CrExportOptions = cryRpt. there you can see CrystalReport1.DiskFileName = _ "c:\crystalExport.

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

ByVal e As System.EventArgs) Handles Button2.ToString) End Try End Sub End Class NOTES: cryRpt.ExportFormatType = ExportFormatType.ExportDestinationType = ExportDestinationType.DiskFileName = _ "c:\crystalExport.FormatOptions = CrFormatTypeOptions End With cryRpt. When you run this program you will get the Excel file (crystalExport.NET For Email a Crystal Reports .rpt .xls" CrExportOptions = cryRpt.Export() Catch ex As Exception MsgBox(ex.Excel . there you can see CrystalReport1.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. we have to export the Crystal Reports in any of the File Format available in Crystal Reports and then Email it. So give the full path name of report here.DiskFile .rpt") The Crystal Report is in your project location.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New ExcelFormatOptions CrDiskFileDestinationOptions. .DestinationOptions = CrDiskFileDestinationOptions .ExportOptions With CrExportOptions .xls) in your computer's C: Email a Crystal Reports from VB.

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

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

Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. there you can see CrystalReport1.Add New Item Dialogue Box. here we are using a Strongly Typed Dataset and a Data Table. Before you run this programme .rpt") The Crystal Report is in your project location. . Crystal Reports Without Database Usually Crystal Reports we are using to fetch data from database and show it as a report. So give the full path name of report here. FROM ADDRESS and TO ADDRESS to the SMTP client. that is your HOSTNAME . The basics of Crystal Reports creation you can find in the previous section of this tutorial .NOTES: cryRpt.rpt . Generating a Strongly Typed DataSet Create a new VB. before we start this tutorial you can take a look at the step by step Crystal Report. Here we are going to generate a Crystal Reports without using a datbase .NET Project and accept the default settings. Create a new Dataset from Project . For generating a Crystal Reports without database . you have to provide the necessary SMTP informations .

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

and select Datatable1 to the right side. . The next screen is to select appropriate data source . Select a new Crystal Reports from Add New Item menu and accept the default settings. Now the dataset part is over .ADO. Next step is to create a Crystal Reports from this Dataset .NET Datasets . so we need two column in the data table . There you can find the Datatable1 from Project data . Add and ID column and Name column in the Data Table. Before going to make Crystal Reports design please take a look at step by step Crystal Report for easy creation of Crystal Reports.Here we are making a two column Crystal Reports .

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

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

Click here to see Database Structure .NET using SQL Query String .Rows.Add("Items") t.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Columns.CrystalReports. Type.Shared Imports System.Tables.GetType("System.GetType("System. Please take a look at the database structure before you start this tutorial .Add(r) Next Dim objRpt As New CrystalReport1 objRpt.Add("Item".Tables(1)) CrystalReportViewer1. . Type.Engine Imports CrystalDecisions.Add("id". Here we create a Strongly Typed dataset for Crystal Reports design and create a connection object and execute the SQL Query String .Click Dim ds As New DataSet1 Dim t As DataTable = ds.ReportSource = objRpt CrystalReportViewer1.Columns.Object.String")) Dim r As DataRow Dim i As Integer For i = 0 To 9 r = t.Refresh() End Sub End Class Crystal Reports from SQL Query String We can create Crystal Reports in VB.EventArgs) Handles Button1.Int32")) t.Imports CrystalDecisions. All Crystal Report programming samples in this tutorials is based on the following database (crystaldb) .SetDataSource(ds.NewRow() r("id") = i r("Item") = "Item" & i t. _ ByVal e As System.

vb) you created in VB." cnn = New SqlConnection(connectionString) cnn.Open() sql = "SELECT Product_id. 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 .EventArgs) Handles Button1.Count) cnn.The basics of Crystal Reports creation you can find in the previous section of this tutorial . Select the default form (Form1.Click Dim ds As New DataSet1 Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=servername.password=password.Product_name. After create the dataset and Crystal Reports design you should create a connection object and fetch the data from database.user id=username. _ initial catalog=crystaldb.SqlClient Imports CrystalDecisions.CrystalReports.Fill(ds. Put the following source code in the button click events Download Source Code Print Source Code Imports System.Shared Imports System.Close() .Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Engine Imports CrystalDecisions.Product_price FROM Product" Dim dscmd As New SqlDataAdapter(sql.NET and drag one button and CrystalReportViewer control to your form.Data. before we start this tutorial you can take a look at the step by step Crystal Report.Object.Rows. cnn) Dim ds As New DataSet1 dscmd. _ ByVal e As System.Tables(1). "Product") MsgBox(ds.

Tables(1)) CrystalReportViewer1. But we can make Crystal Reports from Dynamic column .Dim objRpt As New CrystalReport1 objRpt.Refresh() End Sub End Class NOTE : You have to provide the necessary databse information to Connection String.SetDataSource(ds.ReportSource = objRpt CrystalReportViewer1. That is we enter SQL in textbox and get the Crystal Reports according to the SQL statement. . Crystal Reports from SQL Query String In usual practice . Crystal Reports we are getting from pre defined columns. Here we are going to do the dynamic Crystal Reports from SQL statements .

Here we are limiting as five column . Create a new VB. 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.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 . but you can add any number of column according to your requirements.NET project and add a Strongly Typed Dataset .

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

EventArgs) Handles Button1.CrystalReports.user id=sa.Click Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=SERVERNAME.Shared Imports System.Data Public Class Form1 Dim objRpt As New CrystalReport1 Private Sub Button1_Click(ByVal sender As System.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1. ByVal e As System.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.Engine Imports CrystalDecisions.IndexOf("SELECT") .SqlClient Imports CrystalDecisions.SetDataSource(ds. _ initial catalog=crystaldb.Open() sql = procesSQL() Dim dscmd As New SqlDataAdapter(sql.Data." cnn = New SqlConnection(connectionString) cnn.password=PASSWORD.Download Source Code Print Source Code Imports System.Object. "Product") objRpt.ToUpper selectStart = inSql.Fill(ds.Text inSql = inSql. cnn) Dim ds As New DataSet1 dscmd.

ReportDefinition.selectStart)) lastPart = inSql. " _ & fields(i). Crystal Reports from XML File .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.") firstPart = "" For i = 0 To fields.Text = fields(i).fromStart) fields = firstPart. TextObject) MyText.ToString() & " AS COLUMN" & i + 1 MyText = CType(objRpt.ReportObjects("Text" & _ i + 1).ReportDefinition.Text = fields(i).ReportObjects("Text" _ & i + 1).1 If i > 0 Then firstPart = firstPart & " .Substring(selectStart.fromStart = inSql. TextObject) MyText.ToString() & _ " AS COLUMN" & i + 1 MyText = CType(objRpt.Length .Split(". inSql.Substring(fromStart.ToString() Else firstPart = firstPart & fields(i). (fromStart .IndexOf("FROM") selectStart = selectStart + 6 firstPart = inSql.Length .

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. creating a Crystal Reports from XML file instead of database . Download Product. the only difference is to sslect the data source as your XML file. This is very similer to creating Crystal Reports from database .In this section you can see .XML .

when you select Data for Crsyatl Report .xml ).The basics of Crystal Reports creation provided in previous tutorials . 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. Select all the fields from Product and click finish button . take a look at the tutorial step by step Crystal Report before start this section. if you dont have much knowledge in Crystal Reports . The change happen only from previous report .

net source code in your form and run the program .CrystalReports. So give the full path name of report here. Download Source Code Print Source Code Imports CrystalDecisions.rpt .rpt") CrystalReportViewer1.Click Dim cryRpt As New ReportDocument cryRpt. there you can see CrystalReport1.Object.EventArgs) Handles Button1. When we want to show some additional information about the data in the Crystal Reports .ReportSource = cryRpt CrystalReportViewer1. That is for each row there is a subreoprt for the details. and when user click that hyper link then will get the subreport. _ ByVal e As System. Next step is to select the default form(Form1.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Create a Subreport in Crystal Reports Subreport in Crystal Reports means a Report within a Report . Put the following vb.vb) and add a Button and Crystal Reports Viewer to the Form.Refresh() End Sub End Class cryRpt.Now the designer part is over . This section we are showing the subreport within the Crystal Reports . . that means we put an Hyper link in the row. Subreports we show within the main Crystal Reports and also we can show it as On-Demand report .rpt") The Crystal Report is in your project location.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1. we use the subreports to show the details.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.

Click here to see Database Structure . It will explain in detail the previous section Crystal Report from multiple tables . Here we are using our earlier program Crystal Report from multiple tables to show the main Crystal Reports Data . Create a Crystal Reports using three tables and select customername . date . 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.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 . so please refer Crystal Report from multiple tables before start this section . product and qty . .

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

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

Click Dim crp As New CrystalReport1 CrystalReportViewer1.Engine Imports CrystalDecisions. Next step is to select the default form(Form1.Object.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.net source code in your form and run the program . _ ByVal e As System. Put the following vb.Refresh() End Sub End Class Create a Subreport in Crystal Reports with Link .vb) and add a Button and Crystal Reports Viewer to the Form.ReportSource = crp CrystalReportViewer1.CrystalReports.Now the designer part is over . Download Source Code Print Source Code Imports CrystalDecisions.EventArgs) Handles Button1.

Select the subreport object in the Crystal Reports and right click . then select Format Object . . Here we are creating a subreport . That is when the user click the link . Here we are using our previous example Subreport in Crystal Report and make a link in the min Crystal Reports for on-demand subreport. then only the subreport display. and the subreport has only a link in the main Report .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. on-demand subreports .

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

net source code in your form and run the program .Engine Imports CrystalDecisions. Put the following vb.CrystalReports.Now the designing part is over and you are ready to generate subreport on-demand. _ ByVal e As System.EventArgs) Handles Button1.ReportSource = crp CrystalReportViewer1.Object. Download Source Code Print Source Code Imports CrystalDecisions.Click Dim crp As New CrystalReport1 CrystalReportViewer1.Refresh() End Sub End Class . Next step is to select the default form(Form1.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.vb) and add a Button and Crystal Report Viewer to the Form.

make sure that the following files exist in the \Program Files\Common Files\Merge Modules folder.msm . Also you can distribute the CRRedist2005_x86.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.0\BootStrapper\Packages\CrystalReports . 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. The following steps are creating a setup file for Crystal Reports Client side installation using Merge Modules. Before creating a setup project.msm Microsoft_VC80_ATL_x86. Click the following link to see how to make a setup file with Merge Modules. We can use different approaches to install Crystal Reports runtime files on the target machine .Net Project in a single click. 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.msi file in your system's C:\Program Files\Microsoft Visual Studio 8\SDK\v2. You can find the CRRedist2005_x86.msm policy_8_0_Microsoft_VC80_ATL_x86. If you are using Visual Studio then during your setup and deployment you can add the CRRedist2005_x86. The installer can execute the setup file automatically with your . CrystalReportsRedist2005_x86. A merge module is a set of components that are merged with a Windows installer for applications that need them.msi separately and install it on the target machine.msi file to your setup file and distribute it as a single setup file .

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

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

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

7) Build your project.NET Framework is a software technology that is available with several Microsoft Windows .msm and policy_8_0_Microsoft_VC80_ATL_x86.Then you can see Microsoft_VC80_ATL_x86. and mobile or embedded devices.msm will be automatically added in the Detected Depencies section. Microsoft's . servers.NET Framework is Microsoft's Managed Code programming model for building applications on Windows clients. Microsoft .Net Framework Framework Tutorials The . Either you can add this setup file to you application installer or distribute it as a separate setup file. Now you will get the setup file for distribution.

and each works on a different architecture depends on Operating Systems. 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. that means the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems. Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by Microsoft .Net Framework. Metadata is completely self-describing .Net Framework Microsoft . How to Microsoft . types. Microsoft Intermediate Language (MSIL) is a CPU independent set of instructions that can be converted to the native code. The native code is Operating System independent and this code is known as Managed Code . The Common Language Runtime (CLR) uses metadata to locate and load classes. generate native code. Metadata also created in the course of compile time with Microsoft Intermediate Language (MSIL) and stored it with the compiled code . the language's functionality is managed by the . In the following section you can see how Common Language Runtime (CLR) functions . and execute Managed Code. and it contains information about the members.operating systems.Net Frame work Technology and its related programming models. In the following sections describes . The Common Language Runtime (CLR) provides various Just In Time (JIT) compilers. Metadata is stored in a file called Manifest. the basics of Microsoft . MSIL we can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). that is. references and all the other data that the Common Language Runtime (CLR) needs for execution . Both Microsoft Intermediate Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file. .Net Languages Source Code are compiled into Microsoft Intermediate Language (MSIL) . provide security.NET Framework .

Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes.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 . Common Language Runtime . The .Net Framework manages the code in compile time and run time . The Common Language Runtime (CLR) is the runtime environment of the . The .Net Framework The Microsoft .What is Microsoft .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). that executes and manages all running code like a Virtual Machine.The main two components of .Net Framework .Net Framework Class Library (FCL).Net Framework are Common Language Runtime (CLR) and .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 .

Integrated security and other system services. The CLR ( Common Language Runtime ) defines the Common Type System (CTS). Memory Management that is allocation of Objects and Buffers . The Managed Code compiled only when it needed. and other system services. In the coming section you can see what are the main functions of Common Language Runtime (CLR).NET language that conforms to the Common Language Specification (CLS) have the same primitive Data Types. During the execution of the program . which is a standard type system used by all . Code safety verifications . It works as a layer between Operating Systems and the applications written in . How to Common Language Runtime The Common Language Runtime (CLR) is a an Execution Environment . because during the execution of a program it also controls the interaction with the Operating System.The Common Language Runtime (CLR) is an Execution Environment . that is it converts the appropriate instructions when each function is called . The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. Language integration that is Common Language Runtime (CLR) follow a set of specification called Common Language Specification (CLS) . Exception Handling.Net Framework Class Library (FCL) . The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.Clean up the unused Objects and buffers .NET Managed Code to native code . so Common Language Runtime (CLR) is a language-independent runtime environment . code safety verifications. manage running code like a Virtual Machine and also controls the interaction with the Operating System.Net languages . Common Type System (CTS) that is all .code can be verified to ensure type safety. Common Type System (CTS). this will ensure the interoperability between languages. Common Language Runtime (CLR) manages Thread executions. Exception Handling. Common Language Runtime (CLR)'s main tasks are to convert the . Thread execution.the Common Language Runtime (CLR) manages memory. Garbage Collection (GC) .Net languages that conforms to the Common Language Specification (CLS).NET programming languages uses the same representation for common Data Types . Garbage Collection (GC) . The Common Language Runtime (CLR) environment is also referred to as a managed environment. . That means all .

Common Type System (CTS) describes a set of types that can use different . interfaces. Common Language Specification (CLS) defines a subset of Common Type System (CTS) . The Reference Types are passed by references and stored in the heap.The . regardless of the language used to create the application. and value types that expedite and optimize the development process and provide access to system functionality. The Common Language Runtime (CLR) can load and execute the source code written in .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Most of the members defined by types in the .Net languages have in common . For Communicating between programs written in any . The Classes are accessed by namespaces.Net Framework architecture .Net Complaint languages . those objects must expose the features that are common to all the languages . Moreover.NET Framework. The System Namespace is the root for types in the . which are compatible with the .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces.Net Framework Class Library (FCL) includes a huge collection of reusable classes .Net Framework class library (FCL) provides the core functionality of . That is . The . Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. Namespaces is a logical grouping of types for the purpose of identification. Common Language Specification Common Language Specification (CLS) is a set of basic language features that . The . the types have to be compatible on the basic level . Moreover Common Language Specification (CLS) standardized by ECMA . third-party components can integrate with the classes in the .Net languages can interact with each other.Net Languages needed to develop Applications and Services .NET enabled languages. the Common Type System (CTS) ensure that objects written in different .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.Net Framework class library (FCL) classes are managed classes that provide access to System Services .Net Framework.Net languages in common . which reside within Assemblies. Common Language Specification (CLS) ensures complete interoperability among applications. These types can be Value Types or Reference Types . The . Common Type System Common Type System (CTS) describes a set of types that can be used in different . Framework class library (FCL) provides the consistent base types that are used across all . which ensure that objects written in different languages can interact with each other. The Value Types are passed by values and stored in the stack. When there is a situation to communicate Objects written in different .NET complaint language. The .NET Framework.

Just In Time (JIT) compilation is used to run at high speed.NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. 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. With the help of Just In Time Compiler (JIT) the Common Language Runtime (CLR) doing these tasks.Most of the members defined by types in the . This process is called Just In Time (JIT) compilation. that is it converts the appropriate instructions to the native code for execution just before when each function is called. Just In Time Compiler (JIT) code generally offers far better performance than interpreters. Portable Executable (PE) File Format The Portable Executable (PE) format is a file format for executables. and DLLs. Just In Time (JIT) compilation preserves memory and save time during application initialization.any . That is why the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems without rewrite the source code. Just In Time Compiler The . which is conforms to the Common Language Specification (CLS).Net languages . only if the type is described in the Common Type System (CTS) . Portable Executable File Format is derived from the Microsoft Common Object File Format (COFF). object code.Net language. uses its corresponding runtime to run the application on different Operating Systems . used in 32-bit and 64-bit versions of Windows operating systems. The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each works on a different architecture depending on Operating System. the Managed Code compiled only when it is needed. also known as Dynamic Translation . During the code execution time. after an initial phase of slow interpretation. Managed Code .

Data types. A shared Assembly is one that can be referenced by more than one application. A private Assembly is used only by a single application. The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications. Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. This makes the programs more isolated and at the same time computers are more secure . references and all the other data that the runtime needs for execution. Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. Unmanaged Code can bypass the . . and usually it is stored in that application's install directory. creation and destruction rules. WinMain.Net Assembly Microsoft . Manifest contains information about itself. If multiple applications need to access an Assembly. and design guidelines vary between managed and unmanaged object models. types. On the other hand Unmanaged Code is directly executed by the computer's CPU. or Main). 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'.Net Framework. is the code that has executed by the Common Language Runtime (CLR) environment. we should add the Assembly to the Global Assembly Cache (GAC). error-handling mechanisms. Each Assembly can have only one entry point (that is.Managed Code in Microsoft . 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. Managed code is designed to be more reliable and robust than unmanaged code . with Microsoft Intermediate Language (MSIL). examples are Garbage Collection . We can create two types of Assembly. During the compile time Metadata is created.Net Assembly is a logical unit of code. it contains code that the Common Language Runtime (CLR) executes. private Assembly and shared Assembly . There are two types program files : Process Assemblies (EXE) and Library Assemblies (DLL). . DllMain.NET Framework and make direct calls to the Operating System. Every Assembly you create contains one or more program files and a Manifest. Calling unmanaged code presents a major security risk. This information is called Assembly Manifest. Type Safety etc. and stored in a file called a Manifest . it contains information about the members. The benefits of Managed Code include programmers convenience and enhanced security .

The GAC is automatically installed with the . that allows you to view and manipulate the contents of the Global Assembly Cache. By definition.NET runtime. What are the contents of an Assembly? A . but either types or resources are needed to give the assembly in any meaningful functionality. 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.exe). satellite assemblies can only contain resources. assemblies should contain culture-neutral resources.exe creates an assembly from the . you can place the resources for different languages in different assemblies. They cannot contain any executable code. In general.exe) to compile . Use the Assembly Linker (Al.Defines all types.resources files that you specify. images etc.NET Framework assembly containing resources specific to a given language. their properties and methods.NET static assembly can consist of following elements: a) Assembly Manifest .resources files into satellite assemblies. and the correct assembly is loaded into memory only if the user selects to view the application in that language.Microsoft intermediate language d) A set of Resources . If you want to localize your assembly (for example use different strings for different locales) you should use satellite assemblies. Only the assembly manifest is required. 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. Private Assembly and Shared Assembly . The Global Assembly Cache Tool (Gacutil. What is a Satellite Assembly? A .The Metadata that describes the assembly and its contents b) Type Metadata .All other resources like icons. c) MSIL . Al. Using satellite assemblies.

and a Shared Assembly is a public assembly that is shared by multiple applications. . The .NET . That means. These Classes are organized in a hierarchical tree.NET Framework.A private assembly is an assembly that is available to particular application where they are kept.NET Framework Class Library into a logical grouping according to their functionality. The strong name guarantees the integrity of the assembly which prevents someone from taking over the name of the assembly. What is . a private assembly name need only be unique within the application that uses it. In order to share an assembly. To create a key pair At the command prompt. that means the Assemblies can be assigned a cryptographic signature. The System Namespaces is the root for types in the . We can uniquely identify any Class in the . It is generated from an assembly file using the corresponding private key.net assembly.NET Framework are all built as shared assemblies.Net Namespaces Namespaces are the way to organize . The classes that ship with the . type the following command: sn -k fileName In this command. usability as well as category they should belong to. Strong names guarantee name uniqueness by relying on unique key pairs. 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. version number. or we can say Namespaces are logical grouping of types for the purpose of identification. By contrast. culture identity. the assembly must be explicitly built for this purpose by giving it a cryptographically strong name .Net Strong Name Strong name consists of an Assemblys identity.NET Framework Class Library (FCL ) is a large collection of thousands of Classes. Strong Name includes the name of the . and a public key token. file name is the name of the output file containing the key pair.

All objects created within the same application scope are created within the same application domain. Garbage Collection The . The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the .NET Security Model provides code access permissions and code identity permissions. An application running inside one application domain cannot directly access the code running inside another application domain.Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) . Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code. 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. but it is not immediately freed.In . Code Access Security The . Programmers can also create their own Namespaces in .NET security model that determines whether or not the code is allowed to run. Each application domain has their own virtual address space which scopes the resources for the application domain using that address space. When a program creates an Object. and what resources it can use when it is running. Later when the program has no more references to that Object.Net languages every program is created with a default Namespaces . Application Domain An application domain is a virtual process and is used to isolate applications from one another. Code Access Security is the part of the . the Object takes up the memory. Each application running within its main process boundaries and its application domain boundaries.Framework Class Library (FCL ) by using the full Namespaces of the class .AppDomain is the main class you can use to deal with application domains.this process is called Garbage Collection (GC). System.Net languages. Code Access Security policy uses evidence to help grant the right permissions to the right assembly. Multiple application domains can exist in a single operating system process. the Object's memory becomes unreachable.

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. This releasing of unreferenced Objects is happening automatically in . Thread is like a process. If multiple threads can exist within a process. so it leads improved application performance . Finalization allows a resource to clean up after itself when it is being collected. and share memory and other resources directly. Check the following links to see how Multi Threaded applications works in VB. Multithreading allows multiple process to execute concurrently within a single program . then the memory used by these Objects can be reclaimed. Threads Thread in computer science means a sequence of execution instructions that can run independently . thereby minimizing the use of Operating System resources .Collect. In multiple threaded programming we can use system's idle time. Single thread resulted in systems idle time and application performance.Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System. 1.Net languages by the Garbage Collector (GC). The reclaimed Objects have to be Finalized later. 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. a scheduling priority.That is more than one task in a program can execute at the same time and each thread run independently of its own. Each thread maintains exception handlers. and a set of structures the system uses to save the thread context until it is scheduled.application.GC.NET MultiThreaded Socket Programming . So these unreferenced Objects should be removed from memory . The programming languages like C++. Multithreaded Socket Programming 2. Multi Threaded Chat Server Program VB. Also we can set priority in each Threads .NET . If such Objects exist. It is recommended that you use as few threads as possible. typically share the state information of a process. that is a single flow of execution in a process. then the other new Objects you create can find a place in the Heap. In . at least one thread exists within each process. Threads with higher priority are executed in preference to threads with lower priority.

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

.

the Server create a separate ( independent ) Thread for the each Client request. Then you will get message of "Server started" . 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. 1. Multithreaded Server Socket Program 2.The basic idea behind Multithreaded Socket Programming is. there is a separate Client Thread in Server . That means for each Client. You can start . So the Client can communicate independently with their own Client Thread in Server. whenever Server gets a connection request from Client . Next you start the Client program . then you can see the message from Server . 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 . The Multithreaded Socket Programming has two sections.

Click Try Dim SmtpServer As New SmtpClient() Dim mail As New MailMessage() SmtpServer.Net. For each client Server responds with the Clients Connection ID Number.gmail.com and the port using send mail is 587 .Host = "smtp.Port = 587 SmtpServer. How to send email from VB.Credentials = New _ Net.com") mail.Mail Public Class Form1 Private Sub Button1_Click(ByVal sender As System.In the following example shows how to send an email from a Gmail address. We can instantiate SmtpClient class and assign the Host and Port .ToString) End Try End Sub End Class .To. _ ByVal e As System.Object. The Gmail SMTP server name is smtp.From = New MailAddress("YOURusername@gmail.Send(mail) MsgBox("mail send") Catch ex As Exception MsgBox(ex. but it may vary different Mail Servers .EventArgs) Handles Button1.NET using SMTP protocol for sending email .Net.more than one client same time and communicate with Server . "password") SmtpServer. The default port using SMTP is 25 .Body = "This is for testing SMTP mail from GMAIL" SmtpServer.NET VB.NetworkCredential("username@gmail. VB. SMTP stands for Simple Mail Transfer Protocol .NET using System.Subject = "Test Mail" mail.Mail namespace for send mail . Here using NetworkCredential for password based authentication.com". Download Source Code Print Source Code Imports System.Add("TOADDRESS") mail.com" mail = New MailMessage() mail.gmail.

item _ ("http://schemas.microsoft.You have to provide the informations like your gmail username and password .Fields.com/cdo/configuration/sendusing") _ = cdoSendUsingPickup CDOSYS.Configuration.Configuration.To = "TO ADDRESS" CDOSYS.NET .NET Send email using CDOSYS Using CDOSYS is another easy way to send email from VB. Download Source Code Print Source Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Configuration. and the to address also.TextBody = "Send Email from vb.com/cdo/configuration" & _ /smtpserverpickupdirectory") _ = strPickup CDOSYS. Requirements Windows XP/ Windows2000 Internet Information Services (IIS) SMTP Services in IIS should be enable.Update() CDOSYS.Object.item _ ("http://schemas.net using CDOSYS" . For sending email using CDOSYS .Message") CDOSYS.EventArgs) Handles Button1.Subject = "CDO Test" CDOSYS. VB.Click Dim CDOSYS As Object Const cdoSendUsingPickup = 1 Const strPickup = "c:\inetpub\mailroot\pickup" CDOSYS = CreateObject("CDO. you have to send email from Windows 2000/XP and also you have to be enabled SMTP Service in IIS .microsoft.Fields.From = "FROM ADDRESS" CDOSYS.Fields. ByVal e As System.

Click Dim hostname As IPHostEntry = Dns.GetHostByName(TextBox1.AddressList TextBox2.Net Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Text = ip(0). From Address and it is very important to enable your SMTP services in IIS .Object. Download Source Code Print Source Code Imports System. If you pass localhost in GetHostByName return the IP Address of local machine .Text) Dim ip As IPAddress() = hostname.CDOSYS.net namespace provide the infomation about IP Address . _ ByVal e As System.Send() CDOSYS = Nothing MsgBox("mail send") End Sub End Class You have to provide the informations like To Address .ToString() End Sub End Class . How to find IP Address of Host Syste.EventArgs) Handles Button1.

EventArgs) Handles Button1.GetResponseStream()) TextBox2. _ ByVal e As System. WebResponse return a StreamReader and we can retrieve the content using a StreamReader.How to read a URL Content When we want to read content of an HTML page from a remote webserver .net we are using WebRequest .Text) webresponse = webRequest.GetResponse() inStream = New StreamReader(webresponse.Click Dim inStream As StreamReader Dim webRequest As WebRequest Dim webresponse As WebResponse webRequest = webRequest.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Create(TextBox1.Object. in vb.Net Imports System. WebResponse .ReadToEnd() End Sub End Class .Text = inStream. Download Source Code Print Source Code Imports System.

VB. We need two programs for running a socket program. Once the communication is established .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 . 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 . 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 . the Server and Client can read or write their own sockets. .NET using TCP/IP Communication. In the following section we are going to communicate a Server Socket Program and Client Socket Program through VB. 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.

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

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

it is an instance of the VB. This program act as a Server and listening to clients request . . 1. When Server get the request .NET Console Application Project and put the following source code into project. Create a new VB. Server Socket Program 2. We assign Port 8888 for the Server Socket . Dim serverSocket As New TcpListener(8888) serverSocket.Start() Next step we are creating an infinite loop for continuous communication to Client .The Socket Programming has two sections.NET Console based Application . and call its start() method. Client Socket Program The Server Socket Program here is a VB.NET Class TcpListener . it reads the data from NetworkStream and also write the response to NetworkStream .

GetString(bytesFrom) dataFromClient = _ dataFromClient.Start() msg("Server Started") clientSocket = serverSocket.ASCII.AcceptTcpClient() msg("Accept connection from client") requestCount = 0 Print Source Code While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.ReceiveBufferSize)) Dim dataFromClient As String = _ System.IndexOf("$")) msg("Data from client .ToString(requestCount) Dim sendBytes As [Byte]() = _ Encoding.Download Source Code Imports System.GetStream() Dim bytesFrom(10024) As Byte networkStream.Read(bytesFrom.Substring(0.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex. sendBytes.Text Module Module1 Sub Main() Dim serverSocket As New TcpListener(8888) Dim requestCount As Integer Dim clientSocket As TcpClient serverSocket.Text.Length) networkStream.Sockets Imports System.Close() .Net.Write(sendBytes. 0.GetBytes(serverResponse) networkStream. CInt(clientSocket.Encoding." + dataFromClient) Dim serverResponse As String = _ "Server response " + Convert.ASCII. dataFromClient. 0.ToString) End Try End While clientSocket.

. After create the Client Socket Program . you should first start the Server Socket Program and then start the Client Socket Program .ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Stop() msg("exit") Console. If you need more details about this tutorial please refer to Socket Programming Section .NET Client Socket Program The Socket Programming has two sections. VB.WriteLine(" >> " + mesg) End Sub End Module The next part of this section is Client Socket Program .Trim() Console.serverSocket.

Encoding.0. it reads data from NetworkStream .GetBytes("Message from Client$") serverStream.Net.Connect("127.1". 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.Text. 8888) When client gets connected .Write(outStream.0.Click Dim serverStream As NetworkStream = clientSocket.1. Client Socket Program The Client Socket Program is the continuation of the Server Socket Program .Object. 0. Client connect to the Port 8888 of the Server Socket Program . Server Socket Program 2.Sockets Imports System.Encoding. CInt(clientSocket. and the IP Address (Computer Name) here we give as 127.Sockets. 0. The Client Socket Program is a Windows based application .Text.ASCII.Flush() Dim inStream(10024) As Byte serverStream.0. Download Source Code Print Source Code Imports System.ReceiveBufferSize)) Dim returndata As String = _ System.Read(inStream. _ . because the Server and client running on the same machine .GetStream() Dim outStream As Byte() = _ System.0. and also write to NetworkStream .ASCII. _ ByVal e As System. clientSocket.1 .TcpClient() Dim serverStream As NetworkStream Private Sub Button1_Click(ByVal sender As System. outStream.Object.GetString(inStream) msg("Data from Server : " + returndata) End Sub Private Sub Form1_Load(ByVal sender As System.Net.Length) serverStream.EventArgs) Handles Button1.Text Public Class Form1 Dim clientSocket As New System.

0.NewLine + " >> " + mesg End Sub End Class Brfore you run the Client Socket Program you should start Server Socket Program first .ByVal e As System. VB.Text = "Client Socket Program .1".Text + Environment. In the previous section Socket Programming .NET MultiThreaded Socket Programming Multithreaded Socket Programming means that a Multithreaded Server can communicate with more than one clients at the same time . ..Connect("127. 8888) Label1. take a look at the VB.Text = TextBox1. take a look at Socket Programming before you start this section. From the following figure you can understand how to a Server can communicate with more than one client at the same time ..Server Connected .You can see the basics of Socket Programming in the previous section .NET Socket Programming ." End Sub Sub msg(ByVal mesg As String) TextBox1. the Server Socket Program can communicate with only one client at a time .EventArgs) Handles MyBase. For more details of running this program .0. That means it s not possible to connect another Client Socket Program at the same time to communicate with Server .Load msg("Client Started") clientSocket.

.

You can start . the Server create a separate ( independent ) Thread for the each Client request. Next you start the Client program . there is a separate Client Thread in Server . 1. 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. Multithreaded Server Socket Program 2. then you can see the message from Server .The basic idea behind Multithreaded Socket Programming is. That means for each Client. So the Client can communicate independently with their own Client Thread in Server. The Multithreaded Socket Programming has two sections. whenever Server gets a connection request from Client . 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" .

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

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 .Thread = New Threading.startClient(clientSocket.Close() serverSocket.Trim() Console.serverSocket.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.ToString(counter) + " started!") Dim client As New handleClinet client.Thread(AddressOf doChat) ctThread. _ ByVal clineNo As String) Me.AcceptTcpClient() msg("Client No:" + Convert.ToString(counter)) End While clientSocket.Stop() msg("exit") Console. Convert.clNo = clineNo Dim ctThread As Threading.clientSocket = inClientSocket Me.WriteLine(" >> " + mesg) End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Public Sub startClient(ByVal inClientSocket As TcpClient.Start() msg("Server Started") counter = 0 While (True) counter += 1 clientSocket = serverSocket.

VB. 0.Read(bytesFrom.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.Encoding.Text. CInt(clientSocket.Substring(0. Multithreaded Client Socket Program You have to run Server program first and then Client program . 0.ASCII.NET MultiThreaded Server Socket Programming . Multithreaded Server Socket Program 2.Write(sendBytes.ToString) End Try End While End Sub End Class End Module The Multithreaded Socket Programming has two sections.While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.Length) networkStream. sendBytes.GetStream() networkStream.ToString(requestCount) serverResponse = "Server to clinet(" + clNo + ") " + rCount sendBytes = Encoding.ReceiveBufferSize)) dataFromClient = System. dataFromClient. 1.GetString(bytesFrom) dataFromClient = _ dataFromClient.GetBytes(serverResponse) networkStream.ASCII.IndexOf("$")) msg("From client-" + clNo + dataFromClient) rCount = Convert. then only you can communicate with Server and Client each other .

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

Convert.Trim() Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg. CInt(clientSocket.WriteLine(" >> " + mesg) End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Public Sub startClient(ByVal inClientSocket As TcpClient.ASCII.GetStream() networkStream.startClient(clientSocket. 0.Close() serverSocket.ToString(counter)) End While clientSocket.ReceiveBufferSize)) dataFromClient = System.clNo = clineNo Dim ctThread As Threading.Read(bytesFrom.GetString(bytesFrom) dataFromClient = _ .Thread = New Threading.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.Encoding.Text.Stop() msg("exit") Console.client.clientSocket = inClientSocket Me.Thread(AddressOf doChat) ctThread. _ ByVal clineNo As String) Me.

0. Multithreaded Client Socket Program MultiThreaded Client Socket Program is a windows based application . 0. 1. VB. dataFromClient. Multithreaded Server Socket Program 2.ToString(requestCount) serverResponse = "Server to clinet(" + clNo + ") " + rCount sendBytes = Encoding. Multithreaded Server Socket Program 2. then only you can communicate with Server and Client each other .dataFromClient.ASCII.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 Client Socket Program You have to run Server program first and then Client program . Here the client program is connected to Server's PORT 8888 . because Server and Client program run on the same machine.Length) networkStream.IndexOf("$")) msg("From client-" + clNo + dataFromClient) rCount = Convert. .GetBytes(serverResponse) networkStream. sendBytes.Write(sendBytes.NET MultiThreaded Client Socket Programming The Multithreaded Socket Programming has two sections. 1.0.Substring(0. and IP Address here we give Server Address as " 127.

ReceiveBufferSize serverStream.GetStream() Dim buffSize As Integer Dim outStream As Byte() = _ System. 0.EventArgs) Handles Button1.GetString(inStream) msg("Data from Server : " + returndata) End Sub Private Sub Form1_Load(ByVal sender As System.Sockets Imports System.Click Dim serverStream As NetworkStream = clientSocket.Net.Object. outStream.Load msg("Client Started") clientSocket.Connect("127.. _ ByVal e As System.. 8888) Label1.GetBytes("Message from Client$") serverStream.1". So we can connect more than one client and communicate at the same time.Server Connected .TcpClient() Dim serverStream As NetworkStream Private Sub Button1_Click(ByVal sender As System.Length) serverStream.1". Download Source Code Print Source Code Imports System. the Server make a separate thread for Client's communication . _ ByVal e As System.0.Object.ASCII.Flush() Dim inStream(10024) As Byte buffSize = clientSocket.Encoding.Text. Create a new VB.Net.clientSocket.NET Windows based application and put the following source code in the Project. 0." End Sub Sub msg(ByVal mesg As String) .Text = "Client Socket Program .Encoding.0.0.EventArgs) Handles MyBase.Read(inStream.Text. 8888) When the Client get conncted to the Server .Write(outStream. buffSize) Dim returndata As String = _ System.ASCII.0.Text Public Class Form1 Dim clientSocket As New System.Sockets.Connect("127.

there is no communication between Client to Client .NET TCP Chat Server is handling communication between Client to Client .TextBox1. Multithreaded Client Socket Program You have to run Server program first and then Client program .NewLine + " >> " + mesg End Sub End Class The Multithreaded Socket Programming has two sections. Multithreaded Server Socket Program 2.Text = TextBox1.NET Chat Server Program Multithreaded Socket Programming is the basic idea behind a TCP Chat Server communication.Text + Environment. But there the communication is happening only between Server to Client or Client to Server . a Client can communicate with any number of Clients . From the following diagram you can see how a VB. 1. VB. then only you can communicate with Server and Client each other . Each Clients send messages to Server and the Server broadcast the message to all Clients currently connected to the Chat Server . In a Multithreaded Chat Server . 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 . currently connected on the Chat Server . .

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

The 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 . Similarly you can connect more than one Clients at the same time and start chatting each other. VB. run the Server program first and then run the Client program .exe files . 1. Then you can see the message in the Server program User Joined Chat Room . Chat Client . In the Client program Enter a Chat name and click the " Connect to Server " button . Chat Server 2.How to run Chat Server program ? After create the Chat Server and Chat Client . It is better to Compile and Build the program and run from the .NET Multithreaded Chat Server Program has two sections.

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

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

ReceiveBufferSize)) dataFromClient = System.clientsList = cList Dim ctThread As Threading.GetString(bytesFrom) dataFromClient = _ .Else broadcastBytes = Encoding. 0.clientSocket = inClientSocket Me.ASCII.Encoding. ByVal cList As Hashtable) Me.GetStream() networkStream. 0.ASCII.Read(bytesFrom. _ ByVal clineNo As String.Thread(AddressOf doChat) ctThread.Length) broadcastStream.Thread = New Threading.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.Text. broadcastBytes.Write(broadcastBytes.GetBytes(msg) End If broadcastStream.clNo = clineNo Me.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. CInt(clientSocket.

True) Catch ex As Exception MsgBox(ex.ToString(requestCount) broadcast(dataFromClient.Substring(0. VB. clNo.dataFromClient. Chat Server Download Chat Client Download Refer to Chat Server Program for how to run this program . ." + clNo + " : " + dataFromClient) rCount = Convert. dataFromClient.IndexOf("$")) msg("From client .NET Chat Client The Chat Client is a Windows based Application and its main function is to send message to Chat Server.ToString) End Try End While End Sub End Class End Module Download Chat Server Program .

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

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

Private Declare Function InternetGetConnectedState Lib "wininet" _ (ByRef conn As Long. We can determine it by using one of WinINet function for check the status of internet connection in a computer. 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.GetStream() Dim buffSize As Integer Dim inStream(10024) As Byte buffSize = clientSocket.Read(inStream.Encoding.ASCII. ByVal val As Long) As Boolean . Chat Server Download Chat Client Download Refer to Chat Server Program for how to run this program .ReceiveBufferSize serverStream.GetString(inStream) readData = "" + returndata msg() Next End Sub End Class Download Chat Server Program . such as FTP and HTTP.For infiniteCounter = 1 To 2 infiniteCounter = 1 serverStream = clientSocket.Text. Checking Internet Connection The Microsoft WinINet API enables applications to access standard Internet protocols. buffSize) Dim returndata As String = _ System. 0.

A return value of TRUE from InternetGetConnectedState indicates that at least one connection to the Internet is available. and replace text patterns.Click Dim Out As Integer If InternetGetConnectedState(Out. compare. and modify strings as well as rapidly parse large amounts of text and data to search for. ByVal val As Long) As Boolean Private Sub Button1_Click(ByVal sender As System.EventArgs) Handles Button1. The part before the @ sign is the local part of the address.Runtime. and the part after the @ sign is a domain name to which the email message will be sent . remove. often resulting in long regular expressions.Object. ByVal e As System. Download Source Code Imports System. .InteropServices Public Class Form1 Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef conn As Long.NET Framework provides an extensive set of regular expression tools that enable you to efficiently create. The . feedback@net-informations. 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.com Trying to match these restrictions is a complex task.InternetGetConnectedState function retrieves the connected state of the local system.

ByVal e As System. The classes in the namespace System. The following vb.IO .RegularExpressions Public Class Form1 Private Sub Button1_Click(ByVal sender As System.NET Files VB.com". The pattern parameter consists of various regular expression language elements that symbolically describe the string to match pattern .Regex.EventArgs) Handles Button1.com". The following tutorials provides various operations in Directories as well as Files using System.IsMatch("feedback@net-informations.Text. How to VB.IO provides various methods to retrieve and changes information about Directories and Files . Download Source Code Imports System.IO namespace.IsMatch("feedback@net-informations. String) Indicates whether the specified regular expression finds a match in the specified input string.NET FILE TUTORIALS VB.IsMatch Method (String.9})$" If Regex. pattern) Regex.NET implements its File and Directory operations in the namespace System.NET Directory operations .Object.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\. pattern) Then MsgBox("Valid Email address ") Else MsgBox("Not a valid Email address ") End If End Sub End Class Print Source Code VB.net source code shows how to validate an email address with the help of regular expressions.)+[a-zAZ]{2.Click Dim pattern As String pattern = "^([0-9a-zA-Z]([-\.

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

Move("c:\testDir1\testDir2".destDirName : The destinations directory name.Move("c:\testdir1\testdir2".Exists("c:\testDir1") Then 'shows message if testdir1 exist MsgBox("Directory 'testDir' Exist ") Else 'create the directory testDir1 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.NET source code shows these operations : Download Source Code Print Source Code Imports System.CreateDirectory("c:\testDir1") MsgBox("testDir1 created ! ") 'create the directory testDir2 Directory. "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.Object. .Click If Directory.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System. VB.EventArgs) Handles Button1.NET : Directory.Delete("c:\testDir1") MsgBox("testDir1 deleted ") Directory._ ByVal e As System.Delete("c:\testdir1") The following VB.

Finally it delete the directory testDir1. if File exist it Returns true else Returns false .Create("c:\testFile.txt") How to check a File exist or not ? Before we creating a File object . For that we are using the Exists method in the File class.NET Files operations File class is using for the File operations in VB.Create(FilePath) FilePath : The name of the new File Object File. we usually check that File exist or not.End If End Sub End Class When you executing this program you can see . After the execution you can see testDir in c:\ How to VB. Next the program move the testDir2 to testDir .Exists(FilePath) as Boolean FilePath : The name of the File Boolean : Returns true or false . Syntax : File. first it create directory testDir1 and then testDir2 is creating inside testDir1 . We can create . copy etc. operations do with File class.NET. we can call Create method in the File class. How to create a File ? In order to create a new File . delete . Syntax : File.

txt") How to delete a File Object ? .txt") The following VB.NET source code shows these operations : Imports System.txt File. destFileName : The destinations file name. How to Copy a File ? If we want the Copy of the File Object we can use the Copy method in File class. else it create a new File Object .NET : File. destFileName) sourceFileName : The source file we want to move.VB.EventArgs) Handles Button1.txt") Then 'shows message if testFile exist MsgBox("File 'testFile' Exist ") Else 'create the file testFile. VB. _ ByVal e As System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.txt") MsgBox("File 'testFile' created ") End If End Sub End Class When you execute this source code .Exists("c:\testFile. it first check the File exist or not .txt".Exists("c:\testFile. If exist it shows message file exist . "c:\testDir\testFile. Syntax : Copy(sourceFileName.Copy("c:\testFile.Click If File.Create("c:\testFile.NET : File.Object.

txt") MsgBox("File Copied ") File. How to VB. "c:\testDir\testFile.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System. VB.txt") The following VB.Exists("c:\testFile. if it exist it copied the file to testDir director and it delete the file from the c:\.EventArgs) Handles Button1. We operate File using FileMode in FileStream Class .Delete("c:\testDir\testFile.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.NET source code shows these operations : Download Source Code Print Source Code Imports System. FileStream allows to move data to and from the stream as arrays of bytes.Delete("c:\testFile. if it is not exist it shows message file does not exist.txt") Then MsgBox("FIle not exist ") Else File.NET : File.Copy("c:\testFile.Object.NET FileStream operations The FileStream Class represents a File in the Computer. _ ByVal e As System.txt") MsgBox("file deleted ") End If End Sub End Class When you execute this program first it check whether the file exist or not .txt".Click If Not File.

byteData. FileMode.Length) wFile.Text Public Class Form1 Private Sub Button1_Click(ByVal sender As System. it throws exception FileMode. 0.IO. if the file exist .Click Try Dim wFile As System. if the file does not exist . _ ByVal e As System.ASCII.ToString) End Try End Sub End Class When we execute the program . .Append : Open and append to a file . it create a new file FileMode. Download Source Code Print Source Code Imports System. it create a new File and write the content to it . how to write in a file using FileStream.Write(byteData.GetBytes("FileStream Test1") wFile = New FileStream("streamtest.Close() Catch ex As IOException MsgBox(ex.FileStream Dim byteData() As Byte byteData = Encoding. if the file exist it will append to it FileMode.NET FileStream ? The following example shows .Some of FileModes as Follows : FileMode.Open : Open an existing file How to create a file using VB.EventArgs) Handles Button1.txt".CreateNew : Create a new File .Create : Create a new file .Append) wFile.IO Imports System.Object.

How to VB.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.IO.txt") While True line = readFile. _ ByVal e As System. How to VB.EventArgs) Handles Button1.ReadLine() If line Is Nothing Then Exit While Else MsgBox(line) End If End While readFile.NET Simple TextReader .TextReader = New _ StreamReader("C:\TextReader. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. even though these are not stream classes.Object.Click Try Dim line As String Dim readFile As System.ToString) End Try End Sub End Class When you execute this program the TextReader read the file line by line.NET TextReader operations Textreader and TextWriter are the another way to read and write file respectively.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Download Source Code Print Source Code Imports System.

NET TextWriter Textreader and TextWriter are the another way to read and write file respectively.Close() readFile = Nothing Catch ex As IOException MsgBox(ex. _ ByVal e As System.txt") line = readFile.Click Try Dim line As String Dim readFile As System.ReadToEnd() MsgBox(line) readFile.EventArgs) Handles Button1. even though these are not stream classes. even though these are not stream classes. Read the entire content of the file into a String Download Source Code Print Source Code Imports System. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Download Source Code Imports System.TextReader = New _ StreamReader("C:\Test1. TextReader read the entire file in one stretch. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively.Object.IO.ToString) End Try End Sub End Class When you execute this program .Textreader and TextWriter are the another way to read and write file respectively. The following sample source showing how write in a file using TextWriter . How to VB.IO Public Class Form1 Print Source Code . The following program using TextReader .

Object.txt") writeFile. _ ByVal e As System.Close() writeFile = Nothing Catch ex As IOException MsgBox(ex. you have to first create a FileStream Object and then pass BinaryReader to the constructor method . you will get a file TextWriter.NET BinaryReader BinaryReader Object works at lower level of Streams.EventArgs) Handles Button1. For creating a BinaryReader Object .ToString) End Try End Sub End Class When you execute this source code .net-informations.com") writeFile.txt and inside it written vb. .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.net-informations. Dim readStream As FileStream readStream = New FileStream("c:\testBinary.com How to VB.Flush() writeFile. Binaryreader Object works with Stream Objects that provide access to the underlying bytes.dat".Click Try Dim writeFile As System.WriteLine("vb. FileMode.IO. BinaryReader is used for read premitive types as binary values in a specific encoding stream.Private Sub Button1_Click(ByVal sender As System.TextWriter = New _ StreamWriter("c:\textwriter.

For creating a BinaryWriter Object .dat". you have to first create a FileStream Object and then pass BinaryWriter to the constructor method .Download Source Code Print Source Code Imports System.Open) Dim readBinary As New BinaryReader(readStream) msg = readBinary.dat". Dim writeStream As FileStream writeStream = New FileStream("c:\testBinary. FileMode.NET BinaryWriter The BinaryWriter Object works at lower level of Streams.EventArgs) Handles Button1. How to VB.ToString) End Try End Sub End Class BinaryWriter you can use in the same way to write as binary.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System. FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) . BinaryWriter Object works with Stream Objects that provide access to the underlying bytes. BinaryWriter is used for write premitive types as binary values in a specific encoding stream.ReadString() MsgBox(msg) readStream.Click Dim readStream As FileStream Dim msg As String Try readStream = New FileStream("c:\testBinary.Object. _ ByVal e As System.Close() Catch ex As Exception MsgBox(ex.

FileMode.dat". FileMode. 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.Close() Catch ex As Exception MsgBox(ex.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.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.EventArgs) Handles Button1.Write("This is a test for BinaryWriter !") writeBinay.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay. 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.Object. For creating a BinaryWriter Object .dat". _ ByVal e As System. How to VB. Download Source Code Print Source Code Imports System.Create) Dim writeBinay As New BinaryWriter(writeStream) .NET BinaryWriter The BinaryWriter Object works at lower level of Streams.ToString) End Try End Sub End Class BinaryReader you can use in the same way to read as binary.

txt") IOException is the base class for exceptions thrown while accessing information using streams. File. Delete File The File Class is using the operations such as copying. moving. files and directories. Download Source Code Print Source Code Imports System. True) File.dat".Copy("c:\\temp.Delete("c:\\copytemp. renaming.Object. creating.txt". deleting. Try . "c:\\copytemp. FileMode. How to Copy .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.EventArgs) Handles Button1. opening. FileNotFoundException Class is thrown the exception when an attempt to access a file that does not exist on disk fails.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.txt". and appending to files. _ ByVal e As System.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.Write("This is a test for BinaryWriter !") writeBinay.

NET was built for a disconnected architecture .NET ADO.IO.Delete("c:\\copytemp. .txt") Catch ex As System.'code here Catch ex As System.IO.Net Framework . ByVal e As System.IO.Click Try File. ADO.NET VB.NET Tutorial ADO. Download Source Code Imports System.FileNotFoundException 'exception here End Try The following vb.NET ADO.txt". "c:\\copytemp. which provides communication between relational and nonrelational systems through a common set of components .NET is a data access technology from Microsoft . which is completely independent from the Data Source.ToString()) End Try End Sub End Class Print Source Code VB.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.txt".Object.EventArgs) Handles Button1.FileNotFoundException Class.FileNotFoundException MsgBox(ex.net program shows how to use File Class for copying and deleting a text file and also its shows how to handle System.Copy("c:\\temp. so it enables truly disconnected data access and data manipulation through its Dataset Object. True) File.

NET in details with source code.Net Framework .Net Framework includes mainly three Data Providers for ADO. OLEDB and ODBC are the main Data Providers in the .Net Framework. ADO.NET consist of a set of Objects that expose data access services to the . which provides communication between relational and nonrelational systems through a common set of components .NET are Data Providers and DataSet . The .The two key components of ADO.NET environment. which is completely independent from the Data Source.NET is built for disconnected architecture . . ADO. In the following pages you can see each component of ADO.NET is a data access technology from Microsoft . The Microsoft SQL Server .NET. ADO.NET Architecture ADO. so it enables truly disconnected Data Access and Data Manipulation through its Dataset Object.

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

Net Framework provide the functionality of Data Providers in the ADO. Command Object . Finally the DataAdapter Object .NET. DataSet provides much greater flexibility when dealing with related Result Sets. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data Source. read-only retrieval of query results from the Data Source. The Connection Object provides physical connection to the Data Source. DataSet consists of a collection of DataTable . and it is completely independent from the Data Source. which do not update the data. DataReader Object and DataAdapter Object. DataSet provides a disconnected representation of result sets from the Data Source. forward-only. The DataReader Object is a stream-based . which populate a Dataset Object with results from a Data Source .The four Objects from the . They are Connection Object.

While there are similarities between ADO and ADO. ADO.NET relies on managed providers defined by the .NET.net source code.Net over ADO ADO stands for ActiveX Data Objects and it relies on COM whereas ADO. In the following section you can see each of the ADO. the way they operate and their foundations are quite different. . Advantages of ADO.NET components in details with vb. as well as data sources exposed through OLE DB and XML. The DataAdapter Object provides a bridge between the DataSet and the Data Source.NET CLR (Common Language Runtime).Net over ADO in basic level. The DataTable contains a collection of DataRow and DataCoulumn Object which contains Data. The following are some Advantages of ADO.NET provides consistent access to data sources such as SQL Server.objects that you can relate to each other with DataRelation objects.

You can find more information on ADO to ADO. ADO. ADO recordsets is merely a set of rows retrieved from a data source.A major difference in creating connections with ADO and ADO.NET command object has an ExecuteScalar method which returns the first row and column's value from its associated query. making access faster and more efficient and allowing each namespace to exploit the features of its targeted data provider. ADO.NET gives you the choice of either using client side or server side cursors. In ADO.NET you can create multiple data provider namespaces to connect specifically with a particular data source. ADO objects communicate in binary mode while ADO. Connection Oriented Data Access Architecture and Disconnected Data Access Architecture.NET Framework supports two models of Data Access Architecture. ADO recordsets can hold data from one data source at a time.com/en-us/magazine/cc163954. The ADO.NET is that ADO fits all connections to all types of data sources into a single Connection object.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. 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 from the following link : http://msdn. In the case of Data Communication .NET uses XML for passing the data.NET can have separate Objects that represent connections to different data sources. ADO.microsoft.Net dataset represents in memory representation of a database. The ADO.Net datasets can hold data from various sources and integrate the data and write it back to one or several data sources. ADO.aspx .

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. an open connection must be maintained between your application and the Data Source. Dim ds As New DataSet In Connection Oriented Data Access. the DataSet is not connected directly to a Data Source through a Connection object when you populate it. 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. "connection") Dim ds As New DataSet adapter. 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. Unlike the DataReader.NET Disconnected Data Access Architecture. In these cases the application stays connected to the database system even when it is not using any Database Operations. Dim adapter As New SqlDataAdapter("sql". ADO .NET conserves system resources and provides maximum security for databases and also has less impact on system performance. The DataAdapter acts as a bridge between the Connected and Disconnected Objects. ADO. Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. "Src Table") By keeping connections open for only a minimum period of time.NET ConnectionString . when you read data from a database by using a DataReader object. The DataSet is the central component in the ADO.NET Framework supports two models of Data Access Architecture. A DataSet is an in-memory data store that can hold multiple tables at the same time.Net solves this problem by introduces a new component called Dataset.Fill(ds. ADO.Connected and Disconnected Data Access Architecture The ADO.

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

NET.Net Framework includes mainly three Data Providers for ADO.The .NET. DataReader Object and DataAdapter Object. OLEDB Data Provider and ODBC Data provider. Connection Command DataReader DataAdapter . The following link shows in details about these Objects. Command Object .Net Framework provide the functionality of Data Providers in ADO. SQL Server Connection OLEDB Connection ODBC Connection The four Objects from the . They are the Microsoft SQL Server Data Provider . They are Connection Object. You can see from the following links how these Data Providers making connection to the specified data Sources.

If IsDBNull(ds.How to handle null values ADO.Initial Catalog=DatabaseName.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. In many situations while reading data from Dataset.Tables(0). The function IsDBNull returns True if the data type of expression evaluates to the DBNull type otherwise. Download Source Code Print Source Code Imports System.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. IsDBNull returns False.Object.Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.NET provides database connectivity between relational and non relational systems through a common set of components.Password=Password" sql = "your sql select statements here" . The ADO. the Data Providers and the DataSet.User ID=UserName.Rows(i).NET classes are divided into two components. Conversion from type 'DBNull' to type '' is not valid Here is the solution for how to handle DBNull.Data.Rows(i).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. The DBNull class represents a nonexistent value. ByVal e As System. we have seen the error message like this.Tables(0).EventArgs) Handles Button1.

Open() command = New SqlCommand(sql.Close() Try If IsDBNull(ds. 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.. . Incorrect syntax near '..Item(0))) End If Catch ex As Exception MsgBox(ex.connection = New SqlConnection(connetionString) connection. and return records. because we are trying to insert a single quoted character using in sql statement.Rows(i). execute commands.'.Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds. While we are inserting data into the database table we came across the messages like. We can solve this problem by replace any single quote with two quotes like "Microsoft''s" .Tables(0).SelectCommand = command adapter.Rows(i).NET Data Providers consist of a number of classes used to connect to a data source.Tables(0). the system shows the above error messages.SqlClient.. System.SqlException: Incorrect syntax near .Fill(ds) connection. connection) adapter..Data.ToString()) End Try End Sub End Class How to handle single quotes The Microsoft . For ex: We want to insert a string like "Microsoft's" .

Data.Object. connection) adapter. Public Function convertQuotes(ByVal str As String) As String convertQuotes = str.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.field2) values('" & convertQuotes(field1) & "'.'" & convertQuotes(field2) & "')" Try connection.insert into tablename (field1) values('Microsoft''s') For avoiding each time adding another single quote to the string .Initial Catalog=DatabaseName.ToString) End Try End Sub .InsertCommand = New SqlCommand(sql.EventArgs) Handles Button1.Open() adapter.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.User ID=UserName.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex.Password=Password" connection = New SqlConnection(connetionString) sql = "insert into tablename (field1.NET" connetionString = "Data Source=ServerName. here we implement a function to replace the string with two single quotes. "''") End Function Download Source Code Print Source Code Imports System.InsertCommand. ByVal e As System.Replace("'".

Net Framework includes mainly three Data Providers for ADO. "''") End Function End Class ADO.Net Framework. The Microsoft SQL Server .Replace("'".NET Data Providers help and Tutorial The .NET DATA PROVIDERS HELP AND TUTORIALS ADO.NET. You can see from the following links how these Data Providers making connection to the Data Sources . OLEDB and ODBC are the main Data Providers included in the . SQL Server Connection OLEDB Connection ODBC Connection .'here is the function to handle single quoted characters Public Function convertQuotes(ByVal str As String) As String convertQuotes = str.

with the help of the Connection Object. Depends on the parameter specified in the Connection String . Finally the DataAdapter Object . economy of expression. Command Object . improved control flow. which populate a Dataset Object with results from a Data Source .NET Connection Object connect to the specified Database and open a connection between the application and the Database . 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. to retrieve or manipulate data in the Database. The Connection Object provides physical connection to the Data Source. ADO. forward-only. SQL Commands may be executed. The DataReader Object is a stream-based . Connection should be closed and release the resources . DataReader Object and DataAdapter Object.SpreadsheetGear for .Net Framework provide the functionality of Data Providers in ADO. Once the Database activity is over . ADO.The four Objects from the . and data structures.NET Featuring the fastest and most complete Excel compatible calculation engine . read-only retrieval of query results from the Data Source. which do not update the data.Download a free 30-day evaluation today! C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming.NET Connection Object The Connection Object is a part of ADO. Connection Command DataReader DataAdapter Royalty Free and Excel Compatible . When the connection is established . Written by the developers of C.NET. . They are Connection Object.Net Framework the Connection Object is Handling the part of physical communication between the application and the Data Source. The following link shows in details about these Objects. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data Source.NET Data Provider and it is a unique session with the Data Source. In . More Details.

NET SqlConnection OleDbConnection OdbcConnection C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. The following are the commonly using the connections in the ADO. 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.In ADO. and data structures. Written by the developers of C. improved control flow. economy of expression. More Details ADO.NET the type of the Connection is depend on what Database system you are working with. this book shows you how to start adapting the language now to realize its benefits on today's browsers.NET SQL Server Connection . 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. More Details.

SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. An instance of the SqlConnection class in . Read more. no matter the short survey here.EventArgs) Handles Button1.Password=Password" cnn = New SqlConnection(connetionString) Try cnn. Once the Database activities over .User ID=UserName.The SqlConnection Object is Handling the part of physical communication between the application and the SQL Server Database. The Close method rolls back any pending transactions and releases the Connection from the SQL Server Database. User ID = UserName.Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName. 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. SQL Commands may be executed. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. Password = Password" .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. Initial Catalog = DatabaseName.Object. and over time improve application's design.Data. to retrieve or manipulate data in the database. ByVal e As System. Connection should be closed and release the database resources .Open() MsgBox("Connection Open ! ") cnn. "Legacy" it may be. connetionString = "Data Source = ServerName.. with the help of the Connection Object. Take Learn how to find and create seams in your application.. Imports System.NET Framework is supported the Data Provider for SQL Server Database. The Close() method in SqlConnection class is used to close the Database Connection. When the connection is established .Initial Catalog=DatabaseName.

NET the type of the Connection is depend on what Database system you are working with.NET Data Provider and it is a unique session with the Data Source. Password to the actual names. DatabaseName. Connection should be closed and release the resources . In . The following are the commonly using the connections in the ADO. ADO.From the above statement replace ServerName. with the help of the Connection Object. Once the Database activity is over .NET Connection Object The Connection Object is a part of ADO. ADO. UserName. to retrieve or manipulate data in the Database. In ADO. When the connection is established . SQL Commands may be executed.Net Framework the Connection Object is Handling the part of physical communication between the application and the Data Source.NET Connection Object connect to the specified Database and open a connection between the application and the Database . Depends on the parameter specified in the Connection String .NET SqlConnection OleDbConnection OdbcConnection .

to retrieve or manipulate data in the database. with the help of the Connection Object. SQL Commands may be executed. Read more.User ID=UserName.NET Framework is supported the Data Provider for SQL Server Database.. Working Effectively with Legacy Code Learn how to find and create seams in your application. no matter "Legacy" it may be.Password=Password" cnn = New SqlConnection(connetionString) . Read more.EventArgs) Handles Button1. When the connection is established . ADO.. ByVal e As System.Data. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement.Object.. Connection should be closed and release the database resources . 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.NET SQL Server Connection The SqlConnection Object is Handling the part of physical communication between the application and the SQL Server Database. The Close() method in SqlConnection class is used to close the Database Connection. An instance of the SqlConnection class in .. Once the Database activities over .Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName. no matter "Legacy" it may be.Working Effectively with Legacy Code Learn how to find and create seams in your application.Initial Catalog=DatabaseName.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. and over time improve application's design. and over time improve application's design.

EventArgs) Handles Button1.4.Click Dim connetionString As String Dim cnn As OleDbConnection connetionString = "Provider=Microsoft. with the help of the Connection Object.Open() MsgBox("Connection Open ! ") cnn.OLEDB.Data Source=yourdatabasename.Data. ADO.NET Framework is supported the OLEDB Data Provider.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Try cnn. The Close method rolls back any pending transactions and releases the Connection from the Database connected by the OLEDB Data Provider. Initial Catalog = DatabaseName. UserName.0. Connection should be closed and release the resources .mdb. Download Source Code Print Source Code Imports System. Once the Database activities over . to retrieve or manipulate data in the database. User ID = UserName.Object. DatabaseName. Password = Password" From the above statement replace ServerName. When the connection is established . SQL Commands may be executed." cnn = New OleDbConnection(connetionString) .Jet.NET OLEDB Connection An instance of the OleDbConnection class in .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. Password to the actual names. ByVal e As System. The Close() method in SqlConnection class is used to close the Database Connection. The OleDbConnection instance takes Connection String as argument and pass the value to the Constructor statement.

Data. to retrieve or manipulate data in the database. When the connection is established .mdb.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." From the above statement replace yourdatabasename.Try cnn. Download Source Code Print Source Code Imports System. connetionString = "Provider = Microsoft. The OdbcConnection instance takes Connection String as argument and pass the value to the Constructor statement. The Close() method in SqlConnection class is used to close the Database Connection.EventArgs) Handles Button1. ByVal e As System. The Close method rolls back any pending transactions and releases the Connection from the Database connected by the ODBC Data Provider.NET ODBC Connection An instance of the OdbcConnection class in .mdb to the actual names.0. SQL Commands may be executed.Click . with the help of the Connection Object.4.Object.Jet. Connection should be closed and release the resources . Once the Database activities over . ADO.Open() MsgBox("Connection Open ! ") cnn.OLEDB. Data Source = yourdatabasename.Odbc Public Class Form1 Private Sub Button1_Click(ByVal sender As System.NET Framework is supported the ODBC Data Provider.

ADO. Once the Database activity is over . In . to retrieve or manipulate data in the Database. .NET Data Provider and it is a unique session with the Data Source. DBQ = yourdatabasename.DBQ=yourdatabasename.mdb to the actual names. When the connection is established . with the help of the Connection Object. Depends on the parameter specified in the Connection String .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. Connection should be closed and release the resources ." From the above statement replace yourdatabasename.NET Connection Object The Connection Object is a part of ADO. connetionString = "Driver = {Microsoft Access Driver (*.Open() MsgBox("Connection Open ! ") cnn.mdb.NET Connection Object connect to the specified Database and open a connection between the application and the Database .mdb.Net Framework the Connection Object is Handling the part of physical communication between the application and the Data Source. ADO. SQL Commands may be executed.mdb)}.Dim connetionString As String Dim cnn As OdbcConnection connetionString = "Driver={Microsoft Access Driver (*." cnn = New OdbcConnection(connetionString) Try cnn.mdb)}.

and assign the open connection to the connection property of the Command Object. When the Command Object return result set . you have to create a Connection Object and open a connection to the Data Source.In ADO.NET Command The Command Object in ADO. The Command Object required an instance of a Connection Object for executing the SQL statements. .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. for retrieving data or execute an SQL statement against a Data Source . That is.NET executes SQL statements and Stored Procedures against the data source specified in the Connection Object.NET SqlConnection OleDbConnection OdbcConnection ADO. a Data Reader is used to retrieve the result set.

. ExecuteNonQuery ExecuteReader ExecuteScalar ADO. 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() .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. Also Data Manipulation tasks like Insert .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. Update and Delete perform by ExecuteNonQuery(). Click the following links to see some important built in methods uses in the Command Object to execute the SQL statements. When the CommandType property is set to StoredProcedure. the CommandText property should be set to the name of the stored procedure.

Data.Initial Catalog=DatabaseName.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName.User ID=UserName.EventArgs) Handles Button1.Open() cmd = New SqlCommand(Sql. Initial Catalog = DatabaseName. Password = Password" sql = "Your SQL Statement Here" You have to replace the string with your realtime variables. ByVal e As System.The following example shows how to use the method ExecuteNonQuery() through SqlCommand Object.Object.NET ExecuteNonQuery in OleDbCommand Object . User ID = UserName.Dispose() cnn.ExecuteNonQuery() cmd. ADO.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Password=Password" sql = "Your SQL Statement Here" cnn = New SqlConnection(connetionString) Try cnn. cnn) cmd.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. Download Source Code Print Source Code Imports System.

Data Source = Your mdb filename. Update and Delete perform by ExecuteNonQuery().ExecuteNonQuery() cmd. ByVal e As System.Dispose() cnn.4." sql = "Your SQL Statement Here" cnn = New OleDbConnection(connetionString) Try cnn. cnn) cmd. The following example shows how to use the method ExecuteNonQuery() through 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.Data.OLEDB.0. Also Data Manipulation tasks like Insert .EventArgs) Handles Button1.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() .Jet.Data Source=Your mdb filename.Jet.Close() MsgBox(" ExecuteNonQuery in OleDbConnection executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider = Microsoft. Download Source Code Print Source Code Imports System. ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Open() cmd = New OleDbCommand(sql.0." sql = "Your SQL Statement Here" .OLEDB.4.

If the Result Set is empty it will return a Null reference.NET ExecuteScalar in SqlCommand Object ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. cnn) Dim count As Int32 = Convert. ExecuteScalar() uses fewer System resources.You have to replace the string with your realtime variables.Object. it takes only the first column of first row. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set. Download Source Code Print Source Code Imports System. When compare to ExecuteReader() .Initial Catalog=DatabaseName. ADO. ByVal e As System.Password=Password" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New SqlConnection(connetionString) Try cnn. all other values will ignore. of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ") .Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName.Open() cmd = New SqlCommand(sql.User ID=UserName.ToInt32(cmd.Close() MsgBox(" No. If the Result Set contains more than one columns or rows .EventArgs) Handles Button1.ExecuteScalar()) cmd.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Data.Dispose() cnn. It is very useful to use with aggregate functions like Count(*) or Sum() etc.

0. User ID = UserName.End Try End Sub End Class connetionString = "Data Source = ServerName.Object.OLEDB.Data Source=Your mdb filename.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.ToInt32(cmd. ExecuteScalar() uses fewer System resources.Dispose() .Jet. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set.ExecuteScalar()) cmd.NET ExecuteScalar in OleDbCommand Object ExecuteScalar() in OleDbCommand Object is used for get a single value from Database after its execution. If the Result Set contains more than one columns or rows . ADO. When compare to ExecuteReader() . cnn) Dim count As Int32 = Convert. If the Result Set is empty it will return a Null reference. all other values will ignore. It is very useful to use with aggregate functions like Count(*) or Sum() etc. Download Source Code Print Source Code Imports System.Open() cmd = New OleDbCommand(sql. it takes only the first column of first row. Password = Password" sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables. Initial Catalog = DatabaseName.Data.EventArgs) Handles Button1.4. ByVal e As System.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft." sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New OleDbConnection(connetionString) Try 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. ByVal e As System.Initial Catalog=DatabaseName.Jet. they created only by calling the ExecuteReader method of a Command Object. Download Source Code Print Source Code Imports System.4.Password=Password" . read-only retrieval of query results from the Data Source.cnn.Data.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. it instantiate a SqlClient. The SqlDataReader Object is a stream-based . Data Source = Your mdb filename. forward-only.OLEDB.EventArgs) Handles Button1.SqlDataReader Object. 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." sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables.Object.User ID=UserName.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The SqlDataReader cannot be created directly from code. When the ExecuteReader method in SqlCommand Object execute .0. which do not update the data.

User ID = UserName. it instantiate a OleDb.Dispose() cnn.Read() MsgBox(reader. Password = Password" sql = "Your SQL Statement Here . cnn) reader = cmd.ExecuteReader() While reader. read-only retrieval of query results from the Data Source. like Select * from product" You have to replace the string with your realtime variables.Close() cmd.Item(2)) connetionString = "Data Source = ServerName. ADO. Initial Catalog = DatabaseName." & reader. The OleDbDataReader Object is a stream-based .sql = "Your SQL Statement Here . When the ExecuteReader method in OleDbCommand Object execute .Item(0) & " .Open() cmd = New SqlCommand(sql.OleDbDataReader Object.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class - " & reader. which do not update the data.Item(1) & " End While reader.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.OleDb Print Source Code . like Select * from product" cnn = New SqlConnection(connetionString) Try cnn. The OleDbDataReader cannot be created directly from code.Data. forward-only. Download Source Code Imports System. they created only by calling the ExecuteReader method of a Command Object.

0. Data Source = Your mdb filename. cnn) reader = cmd.EventArgs) Handles Button1.Data Source=Your mdb filename.4." sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.ExecuteReader() While reader.Read() MsgBox(reader.Item(2)) connetionString = "Provider = Microsoft.Jet.0.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Close() cmd." sql = "Your SQL Statement Here like Select * from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql." & reader.OLEDB.Dispose() cnn.Jet. How to ADO.Item(1) & " End While reader. ByVal e As System.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String Dim reader As OleDbDataReader connetionString = "Provider=Microsoft.OLEDB.Object.Item(0) & " .4.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class - " & reader.NET DataReader .

They are SqlDataReader and the OleDbDataReader. forward-only. 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. read-only retrieval of query results from the Data Source. From the following link you can see in details about these classes. The DataReader cannot be created directly from code.ExecuteReader() DataReader Object provides a connection oriented data access to the data Sources.DataReader Object in ADO.OleDb are containing these DataReaders respectively. DataReader. SqlDataReader OleDbDataReader . they created only by calling the ExecuteReader method of a Command Object.Data.Data. DataReader = Command.Raed() There are two types of DataReader in ADO. The System.SqlClient and System.NET is a stream-based . if any row exist . The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row. which do not update the data.NET.

Item(0) & " .ExecuteReader() When the ExecuteReader method in SqlCommand Object execute . like Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Read() Download Source Code Print Source Code Imports System.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName. SqlDataReader. Dim sqlReader As SqlDataReader = sqlCmd. 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.Password=Password" sql = "Your SQL Statement Here . if any row exist .SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Read() MsgBox(sqlReader.Data.EventArgs) Handles Button1.How to ADO. ExecuteReader() in the SqlCommand Object send the SQL statements to SqlConnection Object and populate a SqlDataReader Object based on the SQL statement. sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd." & sqlReader.Open() sqlCmd = New SqlCommand(sql.Item(2)) . it instantiate a SqlClient.User ID=UserName.Item(1) & " End While - " & sqlReader. ByVal e As System.SqlDataReader Object.NET SqlDataReader SqlDataReader Object provides a connection oriented data access to the SQL Server data Sources.Object.ExecuteReader() While sqlReader.Initial Catalog=DatabaseName.

Initial Catalog=DatabaseName.User ID=UserName.Close() sqlCmd.OleDbDataReader Object.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.sqlReader.Data. OleDbDataReader.Click .Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName.Object. How to ADO. ExecuteReader() in the OleDbCommand Object send the SQL statements to OleDbConnection Object and populate an OleDbDataReader Object based on the SQL statement.NET OleDbDataReader OleDbDataReader Object provides a connection oriented data access to the OLEDB Data Sources. ByVal e As System. like Select * from product" You have to replace the string with your realtime variables.EventArgs) Handles Button1.ExecuteReader() When the ExecuteReader method in OleDbCommand Object execute . if any row exist .Read() Download Source Code Print Source Code Imports System.Dispose() sqlCnn. The Read() method in the OleDbDataReader is used to read the rows from OleDbDataReader and it always moves forward to a new valid row.Password=Password" sql = "Your SQL Statement Here . When started to read from an OleDbDataReader it should always be open and positioned prior to the first record. it instantiate an OleDb. Dim oledbReader As OleDbDataReader = oledbCmd.

forward-only.Dispose() oledbCnn." sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbCmd = New OleDbCommand(sql. When the ExecuteReader method in SqlCommand Object execute .4. read-only retrieval of query results from the Data Source.SqlDataReader Object.Item(2)) connetionString = "Provider=Microsoft.Close() oledbCmd.0.4." & oledbReader.0. How to Multiple Result Sets in ADO.ExecuteReader() While oledbReader.Data Source=Your mdb filename. it instantiate a SqlClient." sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.Dim Dim Dim Dim connetionString As String oledbCnn As OleDbConnection oledbCmd As OleDbCommand sql As String connetionString = "Provider=Microsoft.Item(0) & " .Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class - " & oledbReader. which do not update the data.OLEDB. Dim sqlReader As SqlDataReader = sqlCmd.Jet. oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd.NET The DataReader Object is a stream-based .OLEDB.Read MsgBox(oledbReader.Data Source=Your mdb filename.Item(1) & " End While oledbReader.ExecuteReader() .Jet.

For retrieveing multiple ResultSets from SqlDataReader we use the NextResult() method of the SqlDataReader. In this situations the SqlDataReader returns multiple ResultSets also. sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.Data.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName. ByVal e As System.Item(0) & " End While sqlReader.ExecuteReader() While sqlReader.NextResult() In the following source code demonstrating how to get multiple result sets from SqlDataReader() .Item(1)) - " & sqlReader.Initial Catalog=DatabaseName. select top 2 * from ordermaster.EventArgs) Handles Button1.Item(1)) .Item(0) & " " & sqlReader.User ID=UserName.NextResult() While sqlReader. select top 2 * from orderdetails" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Object.Read() MsgBox("From second SQL End While " & sqlReader.Password=Password" sql = "Select top 2 * from product.Open() sqlCmd = New SqlCommand(sql.Read() MsgBox("From first SQL . Download Source Code Print Source Code Imports System." & sqlReader.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.In some situations we need to pass multiple SQL statements to the Command Object. SqlDataReader.

Data. ByVal e As System. forward-only. you can retrieve schema information about the current result set using the GetSchemaTable method.EventArgs) Handles Button1.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName. which do not update the data.Initial Catalog=DatabaseName.SqlDataReader Object.Item(0) & " " & sqlReader.NextResult() While sqlReader.Password=Password" sql = "Select top 2 * from product. When the ExecuteReader method in SqlCommand Object execute . GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result set. Schema Informations from SqlDataReader The SqlDataReader Object is a stream-based .Read() MsgBox("From third SQL End While " & sqlReader.sqlReader.Item(1)) sqlReader.Dispose() sqlCnn. DDim sqlReader As SqlDataReader = sqlCmd. select top 2 * from ordermaster. select top 2 * from orderdetails" You have to replace the string with your realtime variables.User ID=UserName. read-only retrieval of query results from the Data Source. it instantiate a SqlClient.Close() sqlCmd. Download Source Code Print Source Code Imports System.Click .Object.ExecuteReader() While a SqlDataReader is open.

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

Dispose() oledbCnn. oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd. forward-only.Object.EventArgs) Handles Button1. read-only retrieval of query results from the Data Source.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbCmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.0.4.Open() oledbCmd = New OleDbCommand(sql. Download Source Code Print Source Code Imports System. row(column))) Next Next oledbReader.OleDbDataReader Object. ByVal e As System. GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result set.Format("{0} = {1}".ExecuteReader() While a OleDbDataReader is open.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.OLEDB.Columns MsgBox(String.ExecuteReader() Dim schemaTable As DataTable = oledbReader. column.Jet.Data." sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn. which do not update the data.Data Source=Your mdb filename. it instantiate a OleDb.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System. When the ExecuteReader method in oledbCmd Object execute .ColumnName. you can retrieve schema information about the current result set using the GetSchemaTable method.Close() oledbCmd. Dim oledbReader As OleDbDataReader = oledbCmd.Rows For Each column In schemaTable.Close() .The OleDbDataReader Object is a stream-based .

Update and Delete SQL operations . That is the DataAdapter uses the Select statements to fill a DataSet and use the other three SQL commands (Insert. That is these two objects combine to enable both data access and data manipulation capabilities. Insert .Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Data Source=Your mdb filename. From the following links describe how to use SqlDataAdapter and OleDbDataAdapter in detail." sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.NET Data Provider. Update. What is DataAdapter DataAdapter is a part of the ADO.4.OLEDB. The DataAdapter can perform Select .0. delete) to transmit changes back to the Database. The Insert . We can use the DataAdapter in combination with the DataSet Object.Jet. we are using the continuation of the Select command perform by the DataAdapter. DataAdapter provides the communication between the Dataset and the Datasource. SqlDataAdapter . Update and Delete SQL operations in the Data Source.

OleDbDataAdapter What is SqlDataAdapter SqlDataAdapter is a part of the ADO. SqlDataAdapter provides the communication between the Dataset and the SQL database.Object.User ID=UserNamePassword=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.SqlClient namespace. sqlCnn) adapter.Initial Catalog=DatabaseName.SelectCommand = sqlCmd adapter. ByVal e As System. We can use SqlDataAdapter Object in combination with Dataset Object.Data.EventArgs) Handles Button1.Data. Insert etc. it won't directly affect the Database.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. until the user invoke the Update method in the SqlDataAdapter.Open() sqlCmd = New SqlCommand(sql. in the data containing in the Dataset Object .Fill(ds) . 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.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. When the user perform the SQL operations like Select .NET Data Provider and it resides in the System. Download Source Code Print Source Code Imports System.

Download Source Code Print Source Code Imports System. it won't directly affect the Database.Item(1)) connetionString = "Data Source=ServerName.Password=Password" sql = "Select * from product" You have to replace the string with your realtime variables.NET Data Provider and it resides in the System.Tables(0).EventArgs) Handles Button1.OleDb namespace. We can use OleDbDataAdapter Object in combination with Dataset Object.For i = 0 To ds.Tables(0).Initial Catalog=DatabaseName. The OleDbDataAdapter Object and DataSet objects are combine to perform both Data Access and Data Manipulation operations in the OleDb Data Sources. Insert etc.1 MsgBox(ds.Item(0) & " Next adapter.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet . OleDbDataAdapter provides the communication between the Dataset and the OleDb Data Sources.User ID=UserName.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -- " & ds.Tables(0). in the data containing in the Dataset Object . When the user perform the SQL operations like Select .Dispose() sqlCmd.Object. ByVal e As System.Data.Dispose() sqlCnn.Rows(i). until the user invoke the Update method in the OleDbDataAdapter. What is OleDbDataAdapter OleDbDataAdapter is a part of the ADO.Data.Rows.Count .Rows(i).OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.

Rows.Count .Data Source=Your mdb filename.Jet.4. Vb.ExecuteReader() While reader.Rows(i).Data Source=Your mdb filename.OLEDB." sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class ds.NET ExecuteReader and ExecuteNonQuery ExecuteReader : ExecuteReader used for getting the query results as a DataReader object.Item(0) & " -. It is readonly forward only retrieval of records and it uses select command to read through the table from the first to the last.0. Dim reader As SqlDataReader reader = Command." & Next oledbAdapter.Tables(0)." sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.0.Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft. oledbCnn) oledbAdapter.1 MsgBox(ds.4.Read() MsgBox(reader.OLEDB.Tables(0).Tables(0).Rows(i).Item(0)) End While .Jet.Item(1)) connetionString = "Provider=Microsoft.Dispose() oledbCnn.Fill(ds) For i = 0 To ds.Open() oledbAdapter = New OleDbDataAdapter(sql.

command. Dim retValue As Integer Command = New SqlCommand(Sql. ExecuteNonQuery executes the command and returns the number of rows affected. and enhanced with additional security. Connection) retValue = Command.reader. insert. delete etc. set the CommandType of the Command object to StoredProcedure. It is used to execute the sql statements like update. 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. database operations can be encapsulated in a single command. The command Object provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.Close() ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. Using stored procedures. A stored procedure is a precompiled executable object that contains one or more SQL statements.ExecuteNonQuery() Stored Procedures in VB. and DataAdapter Objects.CommandType = CommandType. To call a stored procedure from VB. Command.NET application. DataReader.StoredProcedure .NET The data provider is a set of components that include the Connection. optimized for best performance.

Fill(ds) For i = 0 To ds.StoredProcedure command.SqlClient Public Class Form1 Private Sub Button1.Count .Close() End Sub End Class Stored Procedure with Parameter .User ID=sa.Open() command.Tables(0).Object.Rows(i).NET application.Password=yourpassword" connection = New SqlConnection(connetionString) connection.Tables(0).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.Item(0)) Next connection. ByVal e As System.Click Dim Dim Dim Dim Dim Button1_Click(ByVal sender As System.From the following source code you can see how to call a stored procedure from VB.CommandType = CommandType.1 MsgBox(ds.Connection = connection command.Initial Catalog=PUBS.Data. Download Source Code Imports System.CommandText = "SPPUBLISHER" adapter = New SqlDataAdapter(command) adapter.Rows.

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. command.Parameters.CommandType = CommandType.StoredProcedure param = New SqlParameter("@COUNTRY".NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions. including calling other procedures. execute commands. "Germany") param.The ADO. In many cases stored procedures accept input parameters and return multiple values . and retrieve results. A . Data Providers and DataSet.NET classes are divided into two components. A Stored Procedure contain programming statements that perform operations in the database.NET data provider is used to connect to a database.Direction = ParameterDirection.Input param.Click Dim connetionString As String Dim connection As SqlConnection Print Source Code .Data.String command. Parameter values can be supplied if a stored procedure is written to accept them.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. ByVal e As System.EventArgs) Handles Button1.net. Once the CommandType is set to StoredProcedure.Add(param) The above code passing country parameter to the stored procedure from vb. Download Source Code Imports System.Object.DbType = DbType. you can use the Parameters collection to define parameters. The Command Object in ADO.

Close() End Sub End Class VB.Tables(0).CommandType = CommandType.Count .String command.1 MsgBox(ds.NET DataAdapter with Dataset .Connection = connection command.Direction = ParameterDirection.Password=yourpassword" connection = New SqlConnection(connetionString) connection.Add(param) adapter = New SqlDataAdapter(command) adapter.Rows.DbType = DbType.Open() command. "Germany") param.StoredProcedure command.User ID=sa.Fill(ds) For i = 0 To ds.CommandText = "SPCOUNTRY" param = New SqlParameter("@COUNTRY".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.Item(0)) Next connection.Rows(i).Initial Catalog=PUBS.Input param.Tables(0).NET DATAADAPTER AND DATASET How to ADO.Parameters.

We can use Dataset in combination with DataAdapter class. Similarly a Dataset has no knowledge of the Data Source where the data coming from.EventArgs) Handles Button1. The SqlDataAdapter object allows us to populate Data Tables 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. ByVal e As System.Fill(ds) connection.Initial Catalog=DatabaseName.NET Data Provider.Rows. So the SqlDataAdapter manage the communication between these two Objects. Dataset represents a collection of data retrieved from the Data Source and saving data to the Data Source.Tables(0).Tables(0). Dataadapter with dataset . We can use Fill method of the SqlDataAdapter for populating data in a Dataset.1 MsgBox(ds.Close() For i = 0 To ds.Open() adapter = New SqlDataAdapter("Your SQL Statement Here".Password=Password" connection = New SqlConnection(connetionString) Try connection.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The SqlConnection Object has no information about the data it retrieves .sql sever SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . 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 . connection) adapter.Item(1)) .Data.DataAdapter is a part of the ADO.Object.User ID=UserName.Rows(i).Count .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. Download Source Code Print Source Code Imports System.

Rows(i).4.Open() oledbAdapter = New OleDbDataAdapter("Your SQL Statement Here") oledbAdapter.Close() For i = 0 To ds.Tables(0).OLEDB Data Source OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object .Rows.Jet.Next Catch ex As Exception MsgBox(ex. ByVal e As System.Item(0)) Next .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.EventArgs) Handles Button1.Fill(ds) oledbAdapter." connection = New OleDbConnection(connetionString) Try connection.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.ToString) End Try End Sub End Class Dataadapter with dataset .Data.0. The OleDbConnection Object has no information about the data it retrieves . The OleDbDataAdapter object allows us to populate Data Tables in a DataSet. So the OleDbDataAdapter manage the communication between these two Objects.OLEDB.Tables(0). Similarly a Dataset has no knowledge of the Data Source where the data coming from. 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.Data Source=Your mdb filename.Dispose() connection.Object. We can use Fill method of the OleDbDataAdapter for populating data in a Dataset.1 MsgBox(ds.Count . Download Source Code Print Source Code Imports System.

Count . Download Source Code Print Source Code Imports System.EventArgs) Handles Button1.Tables(0).Item(1)) Next Catch ex As Exception MsgBox(ex.SelectCommand = New SqlCommand("Your SQL Statement Here".ToString) . The SelectCommand property of the SqlDataAdapter is a Command object that retrieves data from the data source.NET Data Provider.Rows.1 MsgBox(ds.Catch ex As Exception MsgBox(ex.Fill(ds) connection.ToString) End Try End Sub End Class Dataadapter SelectCommand .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. SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Close() For i = 0 To ds. connection) adapter.Initial Catalog=DatabaseName.Open() adapter.The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism.Password=Password" connection = New SqlConnection(connetionString) Try connection.Rows(i).Object.Data.User ID=UserName. The following program shows the SqlDataAdapter using its SelectCommand property to retrieve the data from the Data Source.Tables(0).Sql Server SqlDataAdapter is a part of the ADO. ByVal e As System.

Object. ByVal e As System.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.4. The SelectCommand property of the OleDbDataAdapter is a Command object that retrieves data from the data source. connection) oledbAdapter.Close() For i = 0 To ds.NET Data Provider. The following program shows the OleDbDataAdapter using its SelectCommand property to retrieve the data from the Data Source.Tables(0).SelectCommand = New OleDbCommand("Your SQL Statement Here".Jet. Download Source Code Print Source Code Imports System.Data.End Try End Sub End Class Dataadapter SelectCommand .Tables(0).Item(0)) Next Catch ex As Exception MsgBox(ex.Count .OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.ToString) End Try End Sub .OLEDB Data Source OleDbDataAdapter is a part of the ADO.1 MsgBox(ds.EventArgs) Handles Button1." connection = New OleDbConnection(connetionString) Try connection.Rows(i).Data Source=Your mdb filename.OLEDB. The OleDbDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism. OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object.Rows.0.Fill(ds) oledbAdapter.Dispose() connection.Open() oledbAdapter.

Initial Catalog=DatabaseName.Product_price) values(7.Data.OLEDB Data Source .ToString) End Try End Sub End Class Dataadapter InsertCommand . ByVal e As System. In the following Source Code shows how to insert data in the Data Source using SqlDataAdapter and SqlCommand object.'Product7'.InsertCommand = New SqlCommand(sql.Sql Server SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .Product_name.InsertCommand.End Class Dataadapter InsertCommand .Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName.User ID=UserName. Download Source Code Print Source Code Imports System.EventArgs) Handles Button1.700)" Try connection.Password=Password" connection = New SqlConnection(connetionString) sql = "insert into product (Product_id. Open a connection to the Data Source with the help of SqlConnection object and create a SqlCommand object with insert SQL statement. connection) adapter.Open() adapter.Object.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex. and assign the SqlCommand to the SqlDataAdapter's InsertCommand.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The InsertCommand in SqlDataAdapter Object manages to insert the data in the specified Data Source .

the UpdateCommand.NET Data Provider.InsertCommand. The following code samples that demonstrate how to use the SqlDataAdapter object to update a SQL Server database using UpdateCommand properties in SqlDataAdapter." connection = New OleDbConnection(connetionString) sql = "insert into user values('user1'. The InsertCommand in OleDbDataAdapter Object manages to insert the data in the specified Data Source . The InsertCommand.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Data.InsertCommand = New OleDbCommand(sql.OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object . ByVal e As System. . and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications.Open() oledbAdapter.OLEDB. Download Source Code Print Source Code Imports System.Jet.EventArgs) Handles Button1.Data Source=Your mdb filename. that are run on a DataSet object. connection) oledbAdapter.0.ExecuteNonQuery() MsgBox("Row(s) Inserted !! ") Catch ex As Exception MsgBox(ex. Open a connection to the Data Source with the help of OleDbConnection object and create an OleDbCommand object with insert SQL statement.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft. and assign the OleDbCommand to the SqlDataAdapter's InsertCommand.Sql Server SqlDataAdapter is a part of the ADO.4.'password1')" Try connection.Object.ToString) End Try End Sub End Class Dataadapter UpdateCommand . In the following Source Code shows how to insert data in the Data Source using OleDbDataAdapter and OleDbCommand object.

Data.ExecuteNonQuery() MsgBox("Row updated !! ") Catch ex As Exception MsgBox(ex.Initial Catalog=DatabaseName. ByVal e As System.Download Source Code Print Source Code Imports System.UpdateCommand = connection.Data. the UpdateCommand.Click .OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.CommandText = sql adapter. 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.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Open() adapter.NET Data Provider. ByVal e As System.CreateCommand adapter.Object.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName.UpdateCommand.EventArgs) Handles Button1. Download Source Code Print Source Code Imports System.Object.OLEDB Data Source OleDbDataAdapter is a part of the ADO.Password=Password" connection = New SqlConnection(connetionString) sql = "update product set product_price = 1001 where Product_name ='Product7'" Try connection.EventArgs) Handles Button1. The InsertCommand.UpdateCommand.ToString) End Try End Sub End Class Dataadapter UpdateCommand .User ID=UserName.

Sql Server SqlDataAdapter is a part of the ADO. ByVal e As System.Object.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName.CommandText = sql oledbAdapter.Data Source=Your mdb filename. The InsertCommand.User ID=UserName. and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications.Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Initial Catalog=DatabaseName.Password=Password" connection = New SqlConnection(connetionString) .0.Open() oledbAdapter.4.UpdateCommand.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.ToString) End Try End Sub End Class Dataadapter DeleteCommand .NET Data Provider. that are run on a DataSet object." connection = New OleDbConnection(connetionString) sql = "update Users set Password = 'new password' where UserID = 'user1'" Try connection.CreateCommand oledbAdapter.Data.ExecuteNonQuery() MsgBox("Row(s) Updated !! ") Catch ex As Exception MsgBox(ex.UpdateCommand = connection. 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. the UpdateCommand.EventArgs) Handles Button1.Jet.UpdateCommand.OLEDB.

Open() oledbAdapter. The InsertCommand.Jet.DeleteCommand.EventArgs) Handles Button1.OLEDB Data Source OleDbDataAdapter is a part of the ADO. UpdateCommand.DeleteCommand.ToString) End Try End Sub End Class Dataadapter DeleteCommand .OLEDB.ExecuteNonQuery() MsgBox("Row(s) Deleted !! ") ." connection = New OleDbConnection(connetionString) sql = "delete from Users where UserID = 'user1'" Try connection.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.DeleteCommand = connection.NET Data Provider.DeleteCommand.CreateCommand adapter.CommandText = sql adapter.0.DeleteCommand.Data. The OleDbDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism.sql = "delete product where Product_name ='Product7'" Try connection.Data Source=Your mdb filename.4. and DeleteCommand properties of the OleDbDataAdapter are Command objects that manage updates to the specified data source according to modifications.CommandText = sql oledbAdapter.DeleteCommand = connection. Download Source Code Print Source Code Imports System.Open() adapter.Object.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The following Source Code shows how to perform delete data from a database using DeleteCommand property of OleDbDataAdapter.ExecuteNonQuery() MsgBox("Row(s) deleted !! ") Catch ex As Exception MsgBox(ex.CreateCommand oledbAdapter. ByVal e As System.

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. Download Source Code Print Source Code Imports System. connection) cmdBuilder = New SqlCommandBuilder(adapter) .NET DataAdapter is used to manage four separate Command objects.Password=Password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection. The InsertCommand.Initial Catalog=DatabaseName.NET Data Provider. ADO.Open() adapter = New SqlDataAdapter(sql. 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. The SqlCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the SqlCommandBuilder object.ToString) End Try End Sub End Class Dataadapter with CommandBuilder . the UpdateCommand.Catch ex As Exception MsgBox(ex.Object.EventArgs) Handles Button1. ByVal e As System.Data.User ID=UserName. and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object. It closes the Connection when it's done.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Sql Server The DataAdapter is a part of the ADO. 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.

OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Count .Tables(0)) connection. 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.0." .OLEDB The OleDbDataAdapter is a part of the ADO.OLEDB. the UpdateCommand.Object.Item(2) + 100 Next adapter. OleDbDataAdapter is used to manage four separate Command objects.Rows(i).EventArgs) Handles Button1. The InsertCommand. The OleDbCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the OleDbCommandBuilder object.Tables(0).adapter.Data Source=Your mdb filename. Download Source Code Print Source Code Imports System.NET Data Provider.Update(ds.Jet. and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object.ToString) End Try End Sub End Class Dataadapter with CommandBuilder . It closes the Connection when it's done.1 ds.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.Rows.Rows(i).Tables(0). 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.Close() MsgBox("Data updated ! ") Catch ex As Exception MsgBox(ex. ByVal e As System.Fill(ds) For i = 0 To ds.Data.Item(2) = ds.Tables(0).4.

SqlClient Public Class Form1 Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim cmdBuilder As SqlCommandBuilder Print Source Code . The TableMapping Collections help the SqlDataAdapter to do this task.Count . the UpdateCommand.Update(ds.1 ds. Similarly a Dataset has no knowledge of the Data Sourcewhere the data coming from.Close() MsgBox("Email address updates !") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class Dataadapter with DataGridView .Open() oledbAdapter = New OleDbDataAdapter(sql.com" Next oledbAdapter.Item(2) = "neweamil@email. connection) oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) oledbAdapter.Rows.Fill(ds) For i = 0 To ds.Rows(i). The SqlConnection Object has no information about the data it retrieves .Tables(0).Sql Server SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .Data.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code.Tables(0). open a new VB.Tables(0)) connection. The InsertCommand. For running this source code . So the SqlDataAdapter manage the communication between these two Objects. Download Source Code Imports System.connection = New OleDbConnection(connetionString) sql = "select * from tblUsers" Try connection. The following source code demonstrate how to update a Dataset through SqlDataAdapter using a DataGridView. and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object.

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

the UpdateCommand.EventArgs) Handles Button1." connection = New OleDbConnection(connetionString) Sql = "select * from tblUsers" Try connection. The InsertCommand. open a new VB. The TableMapping Collection help the OleDbDataAdapter to do this task.Open() oledbAdapter = New OleDbDataAdapter(Sql. ByVal e As System. So the OleDbDataAdapter manage the communication between these two Objects.Object.Data Source=Your mdb filename.Jet.EventArgs) Handles Print Source Code .0.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code. For running this source code .Object.Fill(ds) DataGridView1.OLEDB. Download Source Code Imports System.Data. connection) oledbAdapter.Click connetionString = "Provider=Microsoft. The following source code demonstrate how to update a Dataset through OleDbDataAdapter using a DataGridView.Data Source= ds. and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object.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 .ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System. Similarly a Dataset has no knowledge of the Data Source where the data coming from.Tables(0) Catch ex As Exception MsgBox(ex. ByVal e As System.4.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.

"columnname3". and Update. and so on.Click Try oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) changes = ds. DataAdapter.Fill(DataTable) The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. using the pattern "columnname1".ToString) End Try End Sub End Class VB.GetChanges() If changes IsNot Nothing Then oledbAdapter. it generates names for the subsequent columns.AcceptChanges() MsgBox("Save changes") Catch ex As Exception MsgBox(ex. "columnname2".Data.IO Imports System.Fill The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data.Fill(DataSet) DataAdapter.Tables(0)) End If ds.Fill method in VB.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 . From the following program you can understand how to use DataAdapter. which changes the data in the data source to match the data in the DataSet. The DataAdapter provides this bridge by mapping Fill. If the data adapter encounters duplicate columns while populating a DataTable. which changes the data in the DataSet to match the data in the data source.NET DataAdapter.Update(ds.NET applications.Button2. Download Source Code Imports System.

A DataSet is made up of a collection of tables.Tables(0).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. Initial Catalog=databasename.Count . . ByVal e As System.Rows(i). Password=password" cnn = New SqlConnection(connectionString) cnn.Close() 'connection close here . cnn) cnn.Rows.NET.Rows.1 MsgBox(dt. that is disconnected from data source sqlAdp.Item(0)) Next 'fetching data from datatable in disconnected mode For i = 0 To dt.Count .1 MsgBox(ds.Fill(dt) 'fetching data from dataset in disconnected mode For i = 0 To ds.Private Sub Button1_Click(ByVal sender As System.EventArgs) Handles Button1. and constraints.Fill(ds) sqlAdp.Rows(i). The DataSet is designed to be used in a disconnected mode.Tables(0). the read or write properties are set to initial values.Tables(0). The following piece of code shows how to fill specific range of rows from DataAdapter to Dataset. DataTable objects are used to represent the tables in a DataSet. In ADO. When an instance of DataAdapter is created.Click Dim i As Integer connectionString = "Data Source=servername. Dim ds As New DataSet In some situations we need to retrieve data only specific range of rows.Object.Tables(0).Open() sqlAdp = New SqlDataAdapter("select * from users". In this situations we can fill the Dataset from DataAdapter only that specific range of rows. User ID=userid. relationships.

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

or it can take either a DataTable as a single argument. 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. additionally we can add new rows and modify the content in a DataTable.NET DATAVIEW TUTORIALS VB. We can use the DataView constructor. and search the data in a DataTable .NET DataView Tutorial The DataView provides different views of the data stored in a DataTable. and search in a DataTable . We can create DataView in two ways.NET ADO. DataView can be used to sort. 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. Changes made to a DataView affect the underlying DataTable automatically.VB. DataViews can be created and configured both design time and run time . DataView can be used to sort. filter. The DataView constructor can be empty. sort criteria.NET ADO. . Either we can use the DataView constructor. That is we can customize the views of data from a DataTable. and a row state filter. filter. or a DataTable along with filter criteria. additionally we can add new rows and modify the content in a DataTable. or we can create a reference to the DefaultView property of the DataTable. or you can create a reference to the DefaultView property of the DataTable.

Object.EventArgs) Handles Button1. and copy and paste the following Source Code on button click event.DataSource = dv Catch ex As Exception MsgBox(ex.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. connection) adapter.Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.NET project and drag a DataGridView and a Button on default Form Form1 . Download Source Code Print Source Code Imports System.SelectCommand = command adapter.NET.DefaultView DataGridView1.Initial Catalog=DatabaseName.Open() command = New SqlCommand(sql.ToString) End Try End Sub End Class . ByVal e As System.DefaultView The following source code shows how to create a DataView in VB.User ID=UserName.Close() dv = ds.Dispose() connection.Tables(0). Create a new VB.Dispose() command.Fill(ds.Tables(0). "Create DataView") adapter.dataView = dataSet.Data.

Fill(ds. and changes made to the underlying DataTable automatically affect any DataView objects that are viewing that DataTable.Dispose() command. The following example creates a View and apply sort on the column Product_Price in descending order.Object. and copy and paste the following Source Code on button click event. "Sort DataView") adapter. "Product_Price > 100".Initial Catalog=DatabaseName.EventArgs) Handles Button1. "Product_Price Desc". Download Source Code Print Source Code Imports System.How to sort DataView The DataView provides different views of the data stored in a DataTable.User ID=UserName. DataView can be used to sort. DataViews can be created and configured at both design time and run time . additionally we can add new rows and modify the content in a DataTable. Changes made to a DataView affect the underlying DataTable automatically. connection) adapter. Create a new VB.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.Open() command = New SqlCommand(sql.Dispose() connection. filter.Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Tables(0). and search data in a DataTable .Close() dv = New DataView(ds.NET project and drag a DataGridView and a Button on default Form Form1 . . We can sort single or multiple fields in a DataView . ByVal e As System. also we can specify the sort order like ASC (ascending) and DESC (descending) .Data.SelectCommand = command adapter.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.

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. filter.DataViewRowState. additionally we can add new rows and modify the content in a DataTable. That is we can customize the views of data from a DataTable. We can create DataView in two ways.User ID=UserName. DataView can be used to sort.EventArgs) Handles Button1.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. and copy and paste the following Source Code on button click event. Create a new VB.Object. or we can create a reference to the DefaultView property of the DataTable. ByVal e As System.NET project and drag a DataGridView and a Button on default Form Form1 . The following source code creates a view that shows all Product Details where the Product Price less than 500. Also we can create multiple DataViews for any given DataTable.Data.Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection. and search a DataTable . Download Source Code Print Source Code Imports System.CurrentRows) DataGridView1.Initial Catalog=DatabaseName.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Either we can use the DataView constructor.Open() .

Dispose() connection. Find returns -1 Dim index As Integer = DataView. Either we can use the DataView constructor.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand .DataSource = dv Catch ex As Exception MsgBox(ex. "Filter DataView") adapter.Dispose() command. only the index of the first matching DataRowView is returned. or we can create a reference to the DefaultView property of the DataTable.command = New SqlCommand(sql.EventArgs) Handles Button1. We can create multiple DataViews for any given DataTable. connection) adapter. The constructor for the DataView class initializes a new instance of the DataView class and accepts the DataTable as an argument.CurrentRows) DataGridView1.Close() dv = New DataView(ds.Fill(ds. If no matches are found. If more than one row matches the search criteria. "Product_Price < = 500".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. We can create DataView in two ways.Find("Product5") Download Source Code Print Source Code Imports System.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.SelectCommand = command adapter. The Find method returns an integer with the index of the DataRowView that matches the search criteria.Tables(0).Data. "Product_Name". DataViewRowState.Object. ByVal e As System. We can search in a DataView according to the sort key values by using the Find method .

Find("Product5") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_id").adapter As New SqlDataAdapter ds As New DataSet dv As DataView sql As String connetionString = "Data Source=ServerName.Close() dv = New DataView(ds.User ID=UserName.Sort = "Product_Name" Dim index As Integer = dv. connection) adapter.ToString() & " End If Catch ex As Exception MsgBox(ex. DataViews can be created and configured at both design time and run time . We can create DataView in two ways.ToString) End Try End Sub End Class Dim Dim Dim Dim " & dv(index)("Product_Name").Tables(0)) dv. or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable. .Open() command = New SqlCommand(sql.Initial Catalog=DatabaseName.Dispose() connection.SelectCommand = command adapter.Dispose() command. "Find Row DataView") adapter. Either we can use the DataView constructor.ToString()) How to add new rows in DataView The DataView provides different views of the data stored in a DataTable.Fill(ds.Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.

The following source code shows how to add new row in a DataView .Object.Dispose() command.Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.EndEdit() dv.Fill(ds.Initial Catalog=DatabaseName.Tables(0)) Dim newRow As DataRowView = dv.Data.Close() dv = New DataView(ds.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.EventArgs) Handles Button1.NET project and drag a DataGridView and a Button on default Form Form1 . ByVal e As System. and copy and paste the following Source Code on button click event. Download Source Code Print Source Code Imports System.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.We can add new rows in the DataView using AddNew method in the DataView.Dispose() connection.AddNew() newRow("Product_ID") = 7 newRow("Product_Name") = "Product 7" newRow("Product_Price") = 111 newRow. connection) adapter. Create a new VB. "Add New") adapter.DataSource = dv .Sort = "product_id" DataGridView1.User ID=UserName.Open() command = New SqlCommand(sql.SelectCommand = command adapter.

EventArgs) Handles Button1. The following source code shows how to update data in a DataView . ByVal e As System.SelectCommand = command adapter. additionally we can add new rows and modify the content in a DataTable.Fill(ds. We can update the data in a DataView .Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. and copy and paste the following Source Code on button click event.Open() command = New SqlCommand(sql. Also we can create multiple DataViews for any given DataTable. We can create DataView in two ways. Download Source Code Print Source Code Imports System.Object. DataView can be used to sort. connection) adapter. and search a DataTable .Initial Catalog=DatabaseName. or we can create a reference to the DefaultView property of the DataTable.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.NET project and drag a DataGridView and a Button on default Form Form1 . "Update") . filter.User ID=UserName. Create a new VB.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. Either we can use the DataView constructor.Catch ex As Exception MsgBox(ex.Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.

Also we can delete the data from the DataView . DataViewRowState.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.DataSource = dv Catch ex As Exception MsgBox(ex.Tables(0).Data.EventArgs) Handles Button1. ByVal e As System. filter. additionally we can add new rows and modify the content in a DataTable. DataView can be used to sort.Object. Download Source Code Print Source Code Imports System.Dispose() connection.adapter.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. "Product_Name".Find("Product5") If index = -1 Then MsgBox("Product not found") Else dv(index)("Product_Name") = "Product11" MsgBox("Product Updated !") End If DataGridView1.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 . The following source code shows how to delete the data from DataView.Dispose() command. "".CurrentRows) Dim index As Integer = dv.Close() dv = New DataView(ds. and search data in a DataTable .

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.

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

Net project successfully . Listener Configuration .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.Net Remoting VB. We can provide .Net Remoting Framework . Try to explore more on Remoting .. Remoting Configurations Configuration provides the necessary information to . We have to provide configuration information to Listener Object and also Client Object . 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. 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..Then you will get the current time from remote Object.config file. Now you have done your first .

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

Singleton objects can be used to share information between multiple clients.Runtime.Serialization. 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. Server activation is normally used when a Remote objects is not required to maintain any state between method calls.Formatters. For SingleCall objects the server will create a single object. Remoting Channel Formatters are used for encoding and decoding the messages before they are transported by the Channel in . 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. Before an Object instance of a Remotable type can be accessed. SingleCall Objects and Singleton Objects belong to Server Activation mode.Net Remoting Channels are used to transport messages to and from the Remote Objects. Channels should be registered before objects are registered. The HTTP channel transports messages to and from remote objects using the SOAP protocol. On the other hand with Singleton mode only one object is created at all. Instead. 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.Net Remoting Framework supports two types of Formatters : Binary Formatter System. it must be created and initialized by Activation process.NET ADO.Runtime. so it can therefore reduce overall performance. it is created as needed. In .Binary and SOAP Formatter . VB.Soap .Net Remoting framework supports Server and Client activation of Remote Objects. The data in binary Formatter has smaller size when compared to SOAP Formatter. execute the method.System.The . The data in a SOAP Formatter larger size compared to Binary Formatter .NET DATASET TUTORIALS . Remoting Channel In . and destroy the object again. When a channel is registered. Channels are Objects that responsible of handling the network protocols and serialization formats.RegisterChannel or by using configuration file. Client Activated objects are instantiated from the client. There are commonly two types of activation modes : Server Activation and Client Activation mode.Net Remoting channel can be implement either by calling the method ChannelServices. The .Net Remote Framework: HTTP channel and TCP channel.Net Remoting Framework. There are two types of Channels available in . so it can be human readable. and the client manages the lifetime of the Remote Object by using a lease-based system provided for that purpose.Formatters.Serialization. The SOAP Formatter is an XML based cross platform text format .

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

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

The following links shows more information of Dataset in details.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The DataSet can be filled either from a data source or dynamically.Object.User . How to Dataset with Sql Server The DataSet contains the copy of the data we requested through the SQL statement. Download Source Code Print Source Code Imports System. The SqlDataAdapter object allows us to populate Data Tables in a DataSet.Initial Catalog=DatabaseName.Data.EventArgs) Handles Button1. We can use Fill method of the DataAdapter for populating data in a Dataset.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.The DataAdapter object allows us to populate DataTables in a DataSet. We can use Dataset in combination with SqlDataAdapter class . We can use Fill method in the SqlDataAdapter for populating data in a Dataset. ByVal e As System. A DataSet can be saved to an XML file and then loaded back into memory very easily.

ID=UserName.Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -" & ds.Dispose() command.Close() For i = 0 To ds.Tables(0).Open() command = New SqlCommand(sql.Tables(0).1 MsgBox(ds.Rows(i).Initial Catalog=DatabaseName. How to Dataset with OLEDB Data Source The DataSet contains the copy of the data we requested through the SQL statement.Dispose() connection. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. We can use Dataset in combination with OleDbDataAdapter class .Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Fill(ds) adapter. Download Source Code Print Source Code .Tables(0). connection) adapter. The OleDbDataAdapter object allows us to populate Data Tables in a DataSet.Item(1)) connetionString = "Data Source=ServerName.Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.SelectCommand = command adapter.Rows(i).Count .Rows.User ID=UserName.

OLEDB.Jet.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.Rows.Fill(ds) oledbAdapter.Tables(0).Imports System.Rows(i).Rows(i).Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.0.Data Source=Your mdb filename.Jet.Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -" & ds.4.4. connection) oledbAdapter.Data Source=Your mdb filename.Tables(0).Dispose() connection.Item(1)) connetionString = "Provider=Microsoft.Object." sql = "Your SQL Statement Here" You have to replace the string with your real time variables.0. ByVal e As System." sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Count .1 MsgBox(ds.Open() oledbAdapter = New OleDbDataAdapter(sql.Tables(0).EventArgs) Handles Button1.Close() For i = 0 To ds. Search Tables in a Dataset Sql Server .OLEDB.

corresponding to the number of rows.Data.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.Dispose() connection.NET source code shows how to find the tables inside the Dataset.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. In some situations we have to find how many tables inside the Dataset Object contains .SelectCommand = command adapter.User ID=UserName.Initial Catalog=DatabaseName. The following VB. The DataTableCollection contains zero or more DataTable objects.Fill(ds. Download Source Code Print Source Code Imports System.Dispose() command.Close() For Each tables In ds.EventArgs) Handles Button1.The DataSet contains DataTableCollection and their DataRelationCollection. ByVal e As System.Open() command = New SqlCommand(sql.Object.TableName) .Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection. "SQL Temp Table") adapter. The SqlDataAdapter object allows us to populate DataTables in a DataSet. The Dataset may comprise data for one or more members. connection) adapter.Tables MsgBox(tables.

User ID=UserName.Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables. Download Source Code Print Source Code Imports System.0.EventArgs) Handles Button1. The data inside Table is in the form of Rows and Columns .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. ByVal e As System.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Search Tables in a Dataset OLEDB Data Source The DataSet contains DataTableCollection and their DataRelationCollection." sql = "Your SQL Statement Here" . The OleDbDataAdapter object allows us to populate DataTables in a DataSet.Jet.Data Source=Your mdb filename.Object.Data. In some situations we have to find how many tables inside the Dataset Object contains .4.Initial Catalog=DatabaseName.NET source code shows how to find the tables inside the Dataset.Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName.OLEDB. The following VB. The DataTableCollection contains zero or more DataTable objects.

connection = New OleDbConnection(connetionString) Try connection.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. connection) oledbAdapter.1 MsgBox(ds. corresponding to the number of rows. The DataSet consists of DataTableCollection and their DataRelationCollection.Object.0.NET source code shows how to find the number of rows in a table that resides in the Dataset.Click Dim connetionString As String .Dispose() connection. Dataset table row count in SQL Server The DataSet contains copy of the data we requested through the SQL statement.Tables(i). Download Source Code Print Source Code Imports System.4. The following VB.Jet.Close() For i = 0 To ds.Data Source=Your mdb filename.Data. "OLEDB Temp Table") oledbAdapter." sql = "Your SQL Statement Here" You have to replace the string with your real time variables.EventArgs) Handles Button1.OLEDB.Count .Tables.TableName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Open() oledbAdapter = New OleDbDataAdapter(sql. The data set may comprise data for one or more members.Fill(ds. The DataTableCollection contains zero or more DataTable objects. ByVal e As System.

Dataset table row count .User ID=UserName.Count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName.Initial Catalog=DatabaseName.Rows.Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.OLEDB Data Source .Close() MsgBox("Number of row(s) " & ds.Initial Catalog=DatabaseName.Open() command = New SqlCommand(sql. connection) adapter.Dispose() connection. "SQL Temp Table") adapter.User ID=UserName.Fill(ds.SelectCommand = command adapter.Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Dispose() command.Tables(0).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.

Fill(ds.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.The DataSet contains copy of the data we requested through the SQL statement." sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Tables(0).Dispose() connection.EventArgs) Handles Button1.Jet.OLEDB.Count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.4.OLEDB.Rows. Download Source Code Print Source Code Imports System.0.Jet.Data. "OLEDB Temp Table") oledbAdapter." sql = "Your SQL Statement Here" . The following VB. ByVal e As System.Data Source=Your mdb filename.0. connection) oledbAdapter.NET source code shows how to find the number of rows in a table that resides in the Dataset from OLEDB Data Source.Object. The DataSet consists of DataTableCollection and their DataRelationCollection.Data Source=Your mdb filename. The DataTableCollection contains zero or more DataTable objects.Close() MsgBox("number of Row(s) " & ds.Open() oledbAdapter = New OleDbDataAdapter(sql. The data inside Table is in the form of Rows and Columns .4.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.

The SqlDataAdapter object allows us to populate DataTable in a DataSet. "SQL Temp Table") . The Dataset can work with the data it contains.You have to replace the string with your real time variables. The Dataset can contains more than one Table at a time. ByVal e As System. How to find column definition . There is a ColumnsCollection object in the Datatable hold the column Definitions. The data inside Table is in the form of Rows and Columns .User ID=UserName.EventArgs) Handles Button1. In some situations we have to find the column headers in a DataTable.Data. Download Source Code Print Source Code Imports System. connection) adapter. without knowing the source of the data coming from.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.Open() command = New SqlCommand(sql.Initial Catalog=DatabaseName. We can use Fill method in the SqlDataAdapter for populating data in a Dataset.SelectCommand = command adapter.Object.Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Fill(ds.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Sql Server Dataset represents a collection of data retrieved from the Data Source.

In some situations we have to find the column headers in a DataTable.Dispose() connection. The Dataset can contain more than one Table at a time.Close() dt = ds.Object.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName.Columns MsgBox(column.Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.Data.Tables(0) For Each column In dt. The OleDbDataAdapter object allows us to populate DataTable in a DataSet. corresponding to the number of rows.Click Dim connetionString As String Dim connection As OleDbConnection .OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System. ByVal e As System. Download Source Code Print Source Code Imports System. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. How to find column definition .User ID=UserName.Dispose() command..Initial Catalog=DatabaseName. The data set may comprise data for one or more members.EventArgs) Handles Button1. There is a ColumnsCollection object in the Datatable hold the column Definitions.OLEDB Data Source Dataset represents a collection of data retrieved from the Data Source.adapter.

0.Columns(i)." sql = "Your SQL Statement Here" You have to replace the string with your real time variables.1 MsgBox(dt. How to create DataSet without Databse Dataset represents a collection of data retrieved from the Data Source. The DataSet contains DataTableCollection and their DataRelationCollection.Jet.Data Source=Your mdb filename.OLEDB.Fill(ds. "OLEDB Temp Table") oledbAdapter.Dispose() connection. connection) oledbAdapter." sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Jet.4.4. The DataTableCollection contains zero or more DataTable objects.Count .Close() dt = ds.Tables(0) For i = 0 To dt.OLEDB.Dim Dim Dim Dim Dim oledbAdapter As OleDbDataAdapter ds As New DataSet dt As DataTable sql As String i As Integer connetionString = "Provider=Microsoft.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Open() oledbAdapter = New OleDbDataAdapter(sql. The data set may comprise data for one or .Columns.Data Source=Your mdb filename.0.

Item(1)) . corresponding to the number of rows.Rows(i).Add(nameCoulumn) dr = dt.Tables(0).1 MsgBox(ds.GetType("System. Type.NewRow() dr("ID") = 2 dr("Name") = "Name2" dt.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Tables(0).Data.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".Rows. Type.Add(dr) ds. ByVal e As System.String")) dt.Tables.Rows(i). For that we manually create a DataTable and add data in it.Rows.Int32")) nameCoulumn = New DataColumn("Name".Count . Download Source Code Print Source Code Imports System.Add(dt) For i = 0 To ds.Columns.Add(dr) dr = dt.Rows.EventArgs) Handles Button1.Columns.Item(0) & " Next i End Sub -" & ds.Add(idCoulumn) dt.Object.Tables(0).NewRow() dr("ID") = 1 dr("Name") = "Name1" dt.more members. We can fill the data in Dataset without calling SQL statements.GetType("System.

connection) adapter.End Class How to multiple tables in Dataset .Object.Initial Catalog=DatabaseName.EventArgs) Handles Button1.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The SqlDataAdapter object allows us to populate DataTables in a DataSet.Fill(ds. "First Table") . The following VB. We can populate Dataset with more than one table at a time using SqlDataAdapter Object . Download Source Code Print Source Code Imports System.SelectCommand = command adapter.NET source code shows how to a single SqlDataAdapter fill Dataset with multiple tables.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.Data.Open() command = New SqlCommand(firstSql. We can use Fill method in the SqlDataAdapter for populating data in a Dataset.User ID=UserName.Sql Server The DataSet contains DataTableCollection and their DataRelationCollection. ByVal e As System.Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection. The DataTableCollection contains zero or more DataTable objects.

CommandText = secondSql adapter.Tables(1). We can populate Dataset with more than one table at a time using OleDbDataAdapter Object .SelectCommand.Dispose() connection.Item(0) & " Next 'retrieve second table data For i = 0 To ds.Item(1)) connetionString = "Data Source=ServerName.Rows(i).Rows.Tables(1). We can use Fill method in the OleDbDataAdapter for populating data in a Dataset.Count .1 MsgBox(ds. How to multiple tables in Dataset .Tables(0). "Second Table") adapter.1 MsgBox(ds.Dispose() command.Rows(i).Close() 'retrieve first table data For i = 0 To ds.Fill(ds.Tables(0).NET source code shows how to a single OleDbDataAdapter fill Dataset with multiple tables.Rows(i).Tables(1).User ID=UserName.Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -- " & ds.Tables(0). The DataTableCollection contains zero or more DataTable objects.Count .Initial Catalog=DatabaseName.Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables. The OleDbDataAdapter object allows us to populate DataTables in a DataSet. .Rows(i).Rows.adapter. The following VB.OLEDB Data Source The DataSet contains DataTableCollection and their DataRelationCollection.Item(1)) -- " & ds.

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

Relations property is an instance of the DataRelationsCollection Object. That is the parent and child column should be similar Data Types.Data.SelectCommand = command adapter.Initial Catalog=DatabaseName. The columns involved in the DataRelation should be identical data types.EventArgs) Handles Button1. The DataSet.Object.User ID=UserName. We can create parent child data relations between DataTable using Datarelation Object. "Table2") .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. ByVal e As System. connection) adapter.CommandText = secondSql adapter.Fill(ds. We can relate one or more column from different tables using DataRelation Object .firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.Fill(ds.Open() command = New SqlCommand(firstSql.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. "Table1") adapter.Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection. Download Source Code Print Source Code Imports System. How to add relations between tables in a Dataset The DataSet contains DataTableCollection and their DataRelationCollection.SelectCommand.

adapter. . We can populate Dataset with more than one table at a time using SqlDataAdapter Object.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.Relations. We can use Fill method in the SqlDataAdapter for populating data in a Dataset.Tables("Table1"). table2Column) 'assign relation to dataset ds. table1Column.Close() 'creating data relations Dim relation As DataRelation Dim table1Column As DataColumn Dim table2Column As DataColumn 'retrieve column table1Column = ds. How to merge tables in a Dataset .Dispose() connection. The SqlDataAdapter object allows us to populate DataTable in a DataSet.User ID=UserName.Initial Catalog=DatabaseName. The DataTableCollection contains zero or more DataTable objects.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.Sql Server The DataSet contains copy of the data we requested through the SQL statement.Dispose() command.Columns(0) 'relating tables relation = New DataRelation("relation".Columns(0) table2Column = ds.Tables("table2").

Dispose() connection.User ID=UserName.Dispose() command.Tables(0).Object.Tables(0) For i = 0 To dt.Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection. "Table(0)") adapter.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Tables(1)) dt = ds.EventArgs) Handles Button1.Data.Open() command = New SqlCommand(firstSql. Download Source Code Print Source Code Imports System.SelectCommand.Fill(ds. "Table(1)") adapter. ByVal e As System.SelectCommand = command adapter.In some situation we want to combine the result of multiple SQL query as a single result set.CommandText = secondSql adapter.Merge(ds. The tables involved in the merge should be identical.Item(1)) .1 MsgBox(dt.Initial Catalog=DatabaseName.Rows.Count .Rows(i).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. In that case we can use the Dataset's Merge method for doing this. connection) adapter.Fill(ds.Item(0) & " Next -" & dt.Rows(i).Close() ds. that is the columns are similar data types .

User ID=UserName. In that case we can use the Dataset's Merge method for doing this.Initial Catalog=DatabaseName. The tables involved in the merge should be identical. ByVal e As System.Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName.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 .Object.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 . Download Source Code Print Source Code Imports System.OLEDB Data Source The DataSet contains copy of the data we requested through the SQL statement.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The OleDbDataAdapter object allows us to populate DataTable in a DataSet. The DataTableCollection contains zero or more DataTable objects.NET source code shows how to merge the tables from two different dataset.Data. In some situation we want to combine the result of multiple SQL query results as a single result set. We can populate Dataset with more than one table at a time using OleDbDataAdapter Object. The following VB. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset.

Dispose() connection. "Second Table") oledbAdapter.Fill(ds1.Count .Close() ds1.Tables(0)) dt = ds1.4.Rows(i).SelectCommand.Fill(ds2. SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server.Merge(ds2. Image is a Datatype in . connection) oledbAdapter.Open() oledbAdapter = New OleDbDataAdapter(firstSql.4.Rows(i).OLEDB.Item(1)) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Item(0) & " Next -" & dt. Insert image in a database ADO.1 MsgBox(dt.Data Source=Your mdb filename.Jet.Jet.CommandText = secondSql oledbAdapter.NET provides database connectivity between relational and non relational systems through a common set of components .Tables(0) For i = 0 To dt. "First Table") oledbAdapter.OLEDB.Rows.Data Source=Your mdb filename.connetionString = "Provider=Microsoft." firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables." firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.0.Tables(0).0.

jpg and stores it to a byte array and then insert it into database.Click connectionString = "Data Source=servername. Download Source Code Imports System. Initial Catalog=databasename.Open() Print Source Code .jpg" If File. [img] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] The above scrip will create a table named as imgtable and adding two column . First you have to create a table that contain an image column .483. Password=password" cnn = New SqlConnection(connectionString) fName = "D:\picfile.147.SQL Server that stores variable length binary data from 0 through 2A31-1 (2. first column is id .Object. an image(img) datatype. The following sql script help you to create a table with Image Datatype column : CREATE TABLE [dbo].an integer datatype and second column is image. User ID=sa. The following VB.NET program shows how to insert an Image in SQL Server.EventArgs) Handles Button1. ByVal e As System.[imgtable]( [id] [int] NULL.NET source code read the image from physical path D:\picfile. The following VB.Data.647) bytes.Exists(fName) Then Dim id As Integer = 1 Dim content As Byte() = ImageToStream(fName) cnn.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.

System. content) cmd.Drawing.img) values ( @id.@img)". date and time data.Parameters.Save(stream.ToArray() End Function End Class Retrieve image from database Managed Providers are a collection of classes in the .Imaging.Jpeg) Catch ex As Exception GoTo tryagain End Try Return Stream.ExecuteScalar(). Byte()) . character data. image data and so on. Dim image As Byte() = DirectCast(command.Dim cmd As New SqlCommand("insert into imgtable (id. Conversion of image data type to another data type is not supported.AddWithValue("@img".AddWithValue("@id".ImageFormat.NET programming model.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.Parameters. implicitly or explicitly. indirect conversion of image data can be performed.ExecuteNonQuery() cnn.NET Framework that provide a foundation for the ADO. id) cmd. However. cnn) cmd. A data type is an attribute that specifies the type of data that the object can hold: integer data.

Like HTML .IO Imports System. Byte()) stream.ExecuteScalar(). cnn) Dim image As Byte() = DirectCast(command.Image = bitmap End Sub End Class Print Source Code VB.NET .Click connectionString = "Data Source=servername. ByVal e As System. User ID=sa.Data.Close() Dim bitmap As New Bitmap(stream) PictureBox1. image.Open() Dim command As New SqlCommand("select img from imgtable where id=1".NET XML TUTORIALS VB. XML is a subset of SGML .The following VB. .Write(image.Object.Standard Generalized Markup Language. Initial Catalog=databasename. Download Source Code Imports System.Length) cnn.NET source code shows how to retrieve an image from SQL Server.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. 0. The following links give you more information about XML Files and its operations through VB.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Private Sub Button1_Click(ByVal sender As System.EventArgs) Handles Button1. Password=password" cnn = New SqlConnection(connectionString) Dim stream As New MemoryStream() cnn.

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

and other operations in XML formatted files . System. These classes are stored in the namespaces like System. The . and over time improve application's design.Xsl etc. You can use any text editor to create an XML file . write.Xml.NET uses XML as its internal storage format. 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. From the following links you can see how to use XML in VB.Xml. The Dataset in ADO. Read more.The .Net Framework provides the Classes for read..Xml.Net technology is widely supported XML file format.Xml. Working Effectively with Legacy Code Learn how to find and create seams in your application.. System.XPath. More over XML files are readable by humans as well as computers. More Details . System.Schema.NET.Xml. no matter "Legacy" it may be.Serialization. System. this book shows you how to start adapting the language now to realize its benefits on today's browsers.

we are using XmlTextWriter class . Download Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming.NET Easily develop websites. improved control flow. "Product 3".Indented writer. The class takes FileName and Encoding as argument. 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.Object. Download Now! Imports System.Indentation = 2 writer. intranets.WriteStartElement("Table") createNode(1. System.Text.WriteEndElement() writer. For creating a new XML file in VB.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Also we are here passing formating details .xml and add four rows in the file.Click Dim writer As New XmlTextWriter("product. economy of expression.Encoding. Print Source Code Download Free CMS for ASP. ByVal e As System. "3000". 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. social networks and e-shops.NET XML is a platform independent language.Close() End Sub Private Sub createNode(ByVal pID As String.EventArgs) Handles Button1. writer) writer.Formatting = Formatting. "1000". ByVal pName As String. "Product 1". ByVal pPrice As String.UTF8) writer. and data structures. More Details. writer) createNode(3.WriteStartDocument(True) writer.WriteEndDocument() writer. Written by the developers of C. writer) createNode(4. "2000".How to create an XML file in VB. "Product 4". ByVal writer As XmlTextWriter) . The following source code creating an XML file product. "4000". writer) createNode(2. "Product 2".xml".NET.

WriteEndElement() writer.WriteString(pName) writer.WriteStartElement("Product_id") writer.WriteStartElement("Product") writer.NET .WriteString(pPrice) writer.WriteEndElement() writer.WriteString(pID) writer.WriteStartElement("Product_price") writer.WriteEndElement() End Sub End Class Output of the above source code : How to open and read an XML file in VB.WriteStartElement("Product_name") writer.writer.WriteEndElement() writer.

Item(0).Trim() & " | " & xmlnode(i).Read) xmldoc. More Details Imports System. In the previous program we create an XML file and named it as products. Download Source Code SpreadsheetGear for ASP. Reading an XML file means that we are reading the information embedded in XML tags in an XML file.ChildNodes.InnerText.ChildNodes. We can read an XML file in several ways depends on our requirement.ChildNodes.NET and WinForms Excel Reporting.Open. Excel compatible charting.Trim() MsgBox(str) Next End Sub End Class . This program read the content in Node wise .Item(0). Here we are using XmlDataDocument class to read the XML file . FileAccess.GetElementsByTagName("Product") For i = 0 To xmlnode.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".IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System. 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.Item(1). The following program read that file and extract the contents inside the XML tag.XML is a self describing language and it gives the data as well as the rules to extract what the data it contains.Xml Imports System.Object.InnerText.ChildNodes.InnerText. Windows Forms spreadsheet controls. ByVal e As System.InnerText. In this program it search the Node < Product > and its child Nodes and extract the data in child nodes.xml. this book shows you how to start adapting the language now to realize its benefits on today's browsers.Trim() & " | " & xmlnode(i).Trim() str = xmlnode(i). dashboards from Excel charts and ranges. FileMode.Count .EventArgs) Handles Button1.Item(2).Load(fs) xmlnode = xmldoc.1 xmlnode(i).

In the previous section we create an XML file using XmlTextWriter Class. 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.XML using an ADO.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. Written by the developers of C. Here we are creating an XML file Product. We can create an XML file in several ways.NET Dataset. Learn more . and data structures.Xml Print Source Code SpreadsheetGear: ASP.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.XML as argument. More Details. improved control flow. Imports System.NET using Dataset XML is a tag based language.Click here to download the input file product. Call the method WriteXml of Dataset and pass the file name Product. economy of expression. For that we have to manually create a Datatable first and add the data of Product. Download Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Then add the Datatable in a Dataset . that means the document is made up of XML tags that contain information.xml <?xml version="1.XML in the Datatable .

Add(New DataColumn("Product_Name". Type.Int32"))) dt.GetType("System. and other operations in XML formatted files . "product1".Add(dt) ds.Tables. Type.NET using ADO.Net Framework provides the Classes for read.Columns. ByVal e As System.String"))) dt.Imports System. write.Click Dim ds As New DataSet dt = New DataTable() dt.Data Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.TableName = "product" ds. "product3". The .Columns. "product2".GetType("System.Add(New DataColumn("product_Price". 4444) ds.Tables(0).NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt. Type.Rows. ByVal pName As String. 1111) fillRows(2.WriteXml("Product. 3333) fillRows(4. "product4".xml") MsgBox("Done") End Sub Private Sub fillRows(ByVal pID As Integer.Dataset XML is a platform independent language.NET .Columns. 2222) fillRows(3.GetType("System.Object. The .Add(New DataColumn("Product_ID".Add(dr) End Sub End Class How to read an XML file in VB. ByVal pPrice As Integer) Dim dr As DataRow dr = dt. so the information formatted in XML can be use in any other platforms (Operating Systems) .Int32"))) fillRows(1. .EventArgs) Handles Button1.Net technology is widely supported XML file format.

NET XML is a general purpose tag based language and very easy to transfer and store data across applications.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Net Framework provides the Classes for read.NET uses XML format as its internal storage format. 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 guidance�and code�you�ll need! Imports System. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. write.xml".Tables(0). ByVal e As System.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. The .Net technology is widely supported XML file format. Click here to download the input file product. New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) Dim i As Integer For i = 0 To ds. Moreover the Dataset in ADO.In the previous section we already saw how to read an XML file through Node navigation .Xml Imports System. Here Dataset is using an XmlReader for read the content of the file. and other operations in XML formatted files .Tables(0).Create("Product.Rows(i).1 MsgBox(ds.Rows. .Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System. The .Item(1)) Next End Sub End Class How to create an XML file from SQL in VB.xml Download Source Code SpreadsheetGear: ASP.Count .Object.EventArgs) Handles Button1. Here we are going to read an XML file using an DataSet.

Windows Forms spreadsheet controls.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Imports System. Download Source Code SpreadsheetGear for ASP.xml") MsgBox("Done") Catch ex As Exception MsgBox(ex.Data.Initial Catalog=databsename.Object.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.Fill(ds) connection. connection) adapter. More Details.Close() ds. Here we are going to create an XML file from Database.WriteXml("Product.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. improved control flow. ByVal e As System.Password=password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.User ID=username. 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.Open() adapter = New SqlDataAdapter(sql. 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. and data structures.EventArgs) Handles Button1.ToString) End Try . dashboards from Excel charts and ranges.NET and WinForms Excel Reporting. Written by the developers of C. Excel compatible charting.Xml Imports System. economy of expression. Call Dataset's WriteXml() method and pass the file name as argument. Make an SQL connection to the Database and execute the sql and store the data in a Datset.

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

Written by the developers of C.Object.XML . Also the Dataset in ADO. We have an XML file Product. 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. Windows Forms spreadsheet controls.xml How to filter data in an XML file XML is a platform independent language.MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_Name"). We are giving a search criteria like the Product_Price >= 3000 and store the result in a newly created XML file Result.Create("Product.XML.ToString()) Click here to download the input file product. Here we are going to filter an XML file content and store the result in a newly created XML file.ToString() & " End If End Sub " & dv(index)("Product_Price"). 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.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.EventArgs) Handles Button1. More Details. Imports System. Excel compatible charting.Click Dim xmlFile As XmlReader xmlFile = XmlReader. If we create an XML file in one platform it can be used in other platforms also. ByVal e As System.NET uses XML format as its internal storage format. Download Source Code SpreadsheetGear for ASP. New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView . improved control flow. so the information formatted in XML can be used in any other platforms (Operating Systems).NET and WinForms Excel Reporting. The . and it has a field Product_Price.xml". and data structures.Net technology is widely supported XML file format. economy of expression. dashboards from Excel charts and ranges.

Net technology is widely supported XML file format. this book shows you how to start adapting the language now to realize its benefits on today's browsers.XML .Click Dim connetionString As String .Object.ReadXml(xmlFile) dv = New DataView(ds.xml") MsgBox("Done") End Sub End Class Click here to download the input file product. 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. DataViewRowState.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Moreover the Dataset in ADO.WriteXml("Result. write. Here we are going to insert the values of an XML file to a Database Table using SQL insert command. After getting the data from XML file to the Dataset . More Details Imports System.CurrentRows) dv. and other operations in XML formatted files .ToTable().EventArgs) Handles Button1.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. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset.Net Framework provides the Classes for read.Tables(0). "Product_price > = 3000".Xml Imports System.ds.Data. Also establish a connection to the Database using a connectionstring . "Product_Name". this book shows you how to start adapting the language now to realize its benefits on today's browsers. ByVal e As System. 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. The .Product.NET uses XML format as its internal storage format. The . Here the Dataset using an XmlReader for read the content of the XML file . we can loop through the dataset values and use insert command to add the values to the Product table in the Databse.

'" & Product_Name & "'.ToDouble(ds.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.Tables(0).Rows.Close() End Sub End Class You have to pass necessary database connection information to connection string. connection) adpter.Item(1) product_Price = Convert.ExecuteNonQuery() Next connection.Count .1 product_ID = Convert. Click here to download the input file product.Initial Catalog=databsename.Tables(0).User ID=username.Rows(i).Create("Product.InsertCommand = command adpter.xml How to create an Excel file from XML .Tables(0).xml".Rows(i).Password=password" connection = New SqlConnection(connetionString) xmlFile = XmlReader.Rows(i).ToInt32(ds." & product_Price & ")" command = New SqlCommand(sql.Item(0)) Product_Name = ds.Item(2)) sql = "insert into Product values(" & product_ID & ".Tables(0). New XmlReaderSettings()) ds.Open() For i = 0 To ds.ReadXml(xmlFile) Dim i As Integer connection.InsertCommand.

Add(misValue) xlWorkSheet = xlWorkBook.Missing. New XmlReaderSettings()) ds. Loop through the Dataset and add the content to the Excel file .Sheets("sheet1") xmlFile = XmlReader.Workbooks. new language for the past year in their work.ApplicationClass xlWorkBook = xlApp.xml".Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.XML is a platform independent language.Office.EventArgs) Handles Button1.Object.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System. For create an excel file you have to add reference of Excel library to you project . Take "Introducing HTML5" is written by developers who have been using the the short survey here.Click Dim xlApp As Excel.ReadXml(xmlFile) . 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.Application Dim xlWorkBook As Excel.Reflection.Interop.Data Imports Excel = Microsoft. XML is a self describing language and it gives the data as well as the rules to identify what the data it contains.Value Dim ds As New DataSet Dim xmlFile As XmlReader Dim i. this book shows you how to start adapting the language now to realize its benefits on today's browsers. Here we are going to read from an XML file content and write the same content to an Excel file.Create("Product. ByVal e As System. j As Integer xlApp = New Excel. More Details Imports System. Using an XmlReader for read the XML file to the Dataset .Xml Imports System. so the information formatted in XML can be used in any other platforms (Operating Systems).

Count .Rows(i).Cells(i + 1.Marshal.Rows.xlsx") xlWorkBook. write.For i = 0 To ds. .Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Net Framework provides the Classes for read.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Runtime.SaveAs("xml2excel.Collect() End Try End Sub End Class Click here to download the input file product.InteropServices.Count .1 xlWorkSheet.Tables(0). The .Item(j) Next Next xlWorkSheet. and other operations in XML formatted files .1 For j = 0 To ds.Columns.Tables(0). j + 1) = _ ds.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.Tables(0).Close() xlApp.

Imports System.OleDb.Data.EventArgs) Handles Button1.Data.TableMappings.Add("Table".xml") Catch ex As Exception MsgBox(ex.0.xls'. ByVal e As System. Here we are using an OleDbConnection to read the excel file and store the content to a Dataset .") MyCommand = New System. 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. More Details Print Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming.ToString) End Try End Sub End Class Click here to download the input excel file xl2xml. improved control flow.OleDbConnection Dim ds As System.Jet. economy of expression.Close() ds. this book shows you how to start adapting the language now to realize its benefits on today's browsers. Written by the developers of C.OLEDB.Data.OleDb.OleDbDataAdapter _ ("select * from [Sheet1$]".0.WriteXml("Product. and data structures. More Details.OleDbDataAdapter MyConnection = New System.Data.Data.DataSet Dim MyCommand As System.Data.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object.OleDb.Extended Properties=Excel 8. 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.Data Source='xl2xml.The following program shows how to create an XML file from an Excel file content . MyConnection) MyCommand.OleDb.DataSet MyCommand.Click Try Dim MyConnection As System. "Product") ds = New System.Fill(ds) MyConnection.xls How to xml to DataGridView . Call the method WriteXml of Datset to write to the XML file.OleDbConnection _ ("provider=Microsoft.4.

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. Phone or Azure. this book shows you how to start adapting the language now to realize its benefits on today's browsers. New XmlReaderSettings()) Dim ds As New DataSet ds.Object. WPF.XML . so the information formatted in XML file can be use in any other platforms .Product.ReadXml(xmlFile) DataGridView1. how to load data in a DataGridView from an XML file .Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System. When the Dataset retrieves the data. Reading an XML file means that we are reading the data embedded in tags in an XML file. .Click Dim xmlFile As XmlReader xmlFile = XmlReader. The . Here the Dataset using an XmlReader for read the content of the XML file .Create("Product. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. not plumbing. Silverlight.xml". More Details Imports System. ASP.NET.Xml Imports System.Net technology is widely supported XML file format.EventArgs) Handles Button1. The following source code shows .DataSource = ds. it passes as DataSource to DataGridView . 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. Download Source Code Professional Code Generator – Free for personal usage Ensure rock-solid foundations for your application while focusing on features. Winforms.XML is a platform independent language.Tables(0) End Sub End Class Click here to download the input file product. ByVal e As System.

Imports System. not plumbing.Object. Silverlight. Phone or Azure.EventArgs) Handles Button1. ByVal e As System. WPF.Click Dim xmldoc As New XmlDataDocument() Dim xmlnode As XmlNode . ASP. intranets.NET Easily develop websites. Here we are reading XML file as Node and pass the Nodes data to TreeView.Xml Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Winforms. social networks and e-shops. Download Source Code Download Free CMS for ASP. Download Now! Print Source Code Professional Code Generator – Free for personal usage Ensure rock-solid foundations for your application while focusing on features.In the previous example we already saw how to read an XML file Node wise.NET.

The . FileMode.ChildNodes For i = 0 To nodeList.Count .Nodes.Open. FileAccess. tNode) End Sub Private Sub AddNode(ByVal inXmlNode As XmlNode.Nodes(0) AddNode(xmlnode. and other operations in XML formatted files .1 xNode = inXmlNode.Nodes. . How to create Crystal Reports from xml .Load(fs) xmlnode = xmldoc.InnerText. Click here to see.Net Framework provides the Classes for read.Add(New TreeNode(xNode.ToString End If End Sub End Class Click here to download the input file tree.Dim fs As New FileStream("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. ByVal inTreeNode As TreeNode) Dim xNode As XmlNode Dim tNode As TreeNode Dim nodeList As XmlNodeList Dim i As Integer If inXmlNode.Nodes.Name)) tNode = inTreeNode.HasChildNodes Then nodeList = inXmlNode.Read) xmldoc. tNode) Next Else inTreeNode.Name)) Dim tNode As TreeNode tNode = TreeView1.Nodes(i) AddNode(xNode.Text = inXmlNode.DocumentElement.ChildNodes(1) TreeView1.ChildNodes(i) inTreeNode. We can use XML as a Data Source to Crystal Reports like a Database . write.xml".Clear() TreeView1.Add(New TreeNode(xmldoc.

XML . the only difference is to sslect the data source as your XML file. This is very similer to creating Crystal Reports from database . 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. creating a Crystal Reports from XML file instead of database .Crystal Reports from XML File In this section you can see . Download Product.

if you dont have much knowledge in Crystal Reports . when you select Data for Crsyatl Report . take a look at the tutorial step by step Crystal Report before start this section.The basics of Crystal Reports creation provided in previous tutorials .xml ). 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. The change happen only from previous report . .

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

Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Net Object to XML How to de-serialize XML to .Net Object to the form of XML or from an XML to .EventArgs) Handles Button1.rpt") The Crystal Report is in your project location. _ ByVal e As System.Refresh() End Sub End Class cryRpt.Net Object How to serialize a .Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt . This is the process of converting an object into a form that can be readily transported.CrystalReports. During XML serialization. How to serialization in xml XML Serialization is the process of serializing a . The .rpt") CrystalReportViewer1. So give the full path name of report here.Net Object. . and other operations in XML formatted files .Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.Imports CrystalDecisions.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.Object. How to serialize a . there you can see CrystalReport1.ReportSource = cryRpt CrystalReportViewer1.Net technology is widely supported XML file format. write.NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. only the public properties and fields of an object are serialized. The . The following links gives you more details about XML Serialization and De-serialization.Net Framework provides the Classes for read. The primary purpose of XML serialization in the .

Columns.GetType("System. 2222) fillRows(3.Tables. 9999) fillRows(2. Here we are using XmlSerializer class for serialize the Dataset Object.Close() ds.GetType("System. "product1". "product3". 3333) fillRows(4. 4444) ds.Add(New DataColumn("Product_Name".NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Columns.Add(dr) End Sub End Class Click here to download serialXML. "product2".Columns.Object.Int32"))) fillRows(1.The following program shows how to serialize a Dataset to an XML disk file .GetType("System.GetType()) xmlWriter.Add(New DataColumn("Product_ID". "product4".String"))) dt.Add(dt) ds.TableName = "product" Dim serialWriter As StreamWriter serialWriter = New StreamWriter("serialXML. ByVal e As System.Click Dim ds As New DataSet dt = New DataTable() dt.Rows. ds) serialWriter. ByVal pPrice As Integer) Dim dr As DataRow dr = dt. Type.Tables(0).Clear() End Sub Private Sub fillRows(ByVal pID As Integer. Type. Download Source Code Print Source Code Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.xml .Int32"))) dt.Serialize(serialWriter. Type.xml") Dim xmlWriter As New XmlSerializer(ds.EventArgs) Handles Button1. ByVal pName As String.Add(New DataColumn("product_Price".

Net Object XML is a general purpose tag based language and very easy to transfer and store data across applications.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 .0" encoding="UTF-8"?> <DataSet><xs:schema xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www. Download Source Code Print Source Code . The following source code shows how to de-serialize the DataSet as it is streamed from an XML file back into memory.Net Object to the form of XML file or from an XML to . only the public properties and fields of an object are serialized.Net Object.w3. During XML serialization.<?xml version="1. XML Serialization is the process of serializing a .

All cells derive from the DataGridViewCell base class. FileMode.NET DataGridView Tutorial The following lessons teaches you the fundamental programming concepts of DataGridView control and its supporting classes. such as text format. The cell is the fundamental unit of interaction for the DataGridView. The DataGridView control provides a customizable table for displaying data.GetType) Dim readStream As FileStream = New FileStream("serialXML. ByVal e As System. Also the DataGridView class allows us to customization of cells. font etc. This control is designed to be a complete solution for displaying tabular data with Windows Forms. rows.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.xml".DataSource = ds.Deserialize(readStream). Each cell within the DataGridView control can have its own style.Tables(0) End Sub End Class VB. foreground color. background color.Xml.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.Serialization Imports System. . 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.NET DATAGRIDVIEW TUTORIALS VB.Imports System. The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values.Object. in detail.Open) ds = CType(xmlSerializer.EventArgs) Handles Button1.Close() DataGridView1. columns. DataSet) readStream.

Click Dim connectionString As String = "Data Source=.Close() DataGridView1.Open() dataadapter. The DataGridView control can display rows of data from a data . One very common use of the DataGridView control is binding to a table in a database.OLEDB in VB.NET The DataGridView can display data in Bound mode and unbound mode and Virtual mode.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Bound mode is suitable for managing data using automatic interaction with the data store.DataSource = ds DataGridView1. The following vb.Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql.. ByVal e As System. Download Source Code Print Source Code Imports System.we chose the Pubs database. "Authors_table") connection.Sql Server You can extend the DataGridView control in a number of ways to build custom behaviors into your applications.EventArgs) Handles Button1.The following lessons explain the basics of DataGridView control and steps through an example that builds simple vb. VB.DataMember = "Authors_table" End Sub End Class DataGridView binding . which comes with SQL Server .NET DataGridView binding .Initial Catalog=pubs. The DataGridView can display data in Bound mode. as our target database.net programs. connection) Dim ds As New DataSet() connection. 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 easiest way to get started using the DataGridView control is to use it in basic data binding scenarios.net program shows how to bind a SQL Server dataset in a DataGridView. unbound mode and Virtual mode . All the source code in the following examples .Object.Data.Fill(ds.

ByVal e As System.net program shows how to bind an OLEDB dataset in a DataGridView. The following vb.Close() DataGridView1.net program shows how to filter and sort a DataGridView by using a DataView Object.EventArgs) Handles Button1.mdb path". Dim dv As DataView dv = New DataView(ds." Dim sql As String = "SELECT * FROM Authors" Dim connection As New OleDbConnection(connectionString) Dim dataadapter As New OleDbDataAdapter(sql.Object.Fill(ds.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.DataMember = "Authors_table" End Sub End Class DataGridView Sorting/Filtering in VB.0.Open() dataadapter. "Authors_table") connection.DataSource = ds DataGridView1. connection) Dim ds As New DataSet() connection. When you specify a data source for the DataGridView.OLEDB. "Price > 19". You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. This will be created based on the data types in the data source.NET The DataGridView control provides a customizable table for displaying data. Download Source Code Print Source Code Imports System.Data Source="Your . The following vb. A DataView provides a means to filter and sort data within a DataTable.source.Tables(0).Click Dim connectionString As String = "Provider=Microsoft.Data.DataSource = dv . "Price Desc".CurrentRows) DataGridView1.4. DataViewRowState. by default it will construct columns for you automatically.Jet.

Click DataGridView1.Data. Alternatively. The DataGridView control is highly configurable and extensible.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.DataSource = dv End Sub End Class DataGridView adding rows and columns in VB. methods.Fill(ds. and it provides many properties. "Titles_table") connection. "Price Desc".Columns(Index).SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object. DataGridView1.NET The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms. DataViewRowState. "Price > 19".Initial Catalog=pubs.Data.CurrentRows) DataGridView1. ByVal e As System. ByVal e As System. you can add rows and columns to the control and manually populate it with data.Name = "Column Name" Download Source Code Print Source Code Imports System.Tables(0). and events to customize its appearance and behavior.Download Source Code Print Source Code Imports System.Click Dim connectionString As String = "Data Source=. connection) Dim ds As New DataSet() connection.Columns(0).net source code shows how to manually create Columns and Rows in a DataGridView.Close() Dim dv As DataView dv = New DataView(ds.EventArgs) Handles Button1.Name = "Product ID" .Object.EventArgs) Handles Button1.ColumnCount = 3 DataGridView1..Integrated Security=True" Dim sql As String = "SELECT * FROM Titles" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql. The following vb. The DataGridView control is used to display data from a variety of external data sources.Open() dataadapter.

Add(row) .Visible = False Download Source Code Print Source Code Imports System. Displaying data in a tabular format is a task you are likely to perform frequently.EventArgs) Handles Button1.ColumnCount = 3 DataGridView1.Object.Rows.Columns(0).Columns(Index). "2000"} DataGridView1.Add(row) row = New String() {"4".Name = "Product Name" DataGridView1. "3000"} DataGridView1.Name = "Product_Price" Dim row As String() = New String() {"1".Add(row) End Sub End Class DataGridView hiding rows and columns in VB.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Columns(2).Rows. "1000"} DataGridView1.Columns(2).Click DataGridView1.Add(row) row = New String() {"3".Columns(1).Data. "Product 1". ByVal e As System.Rows.NET The DataGridView control provides a customizable table for displaying data.Add(row) row = New String() {"2". The following vb.Name = "Product_Price" Dim row As String() = New String() {"1". "1000"} DataGridView1. The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms . "Product 1".Name = "Product Name" DataGridView1. "Product 4". "4000"} DataGridView1. methods and events to customize its appearance and behavior.Rows.Visible = False DataGridView1.Rows.Columns(1). "Product 3". "Product 2".Name = "Product ID" DataGridView1. It gives you number of properties.net source code manually creates a DataGridView columns and rows and hide the second column and second row.DataGridView1.Rows(Index). DataGridView1.

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

rows. If a DataGridView has lot of rows then we can implement paging functionalities to the DataGridView control.SqlClient Public Class Form1 Dim pagingAdapter As SqlDataAdapter Dim pagingDS As DataSet Dim scrollVal As Integer Print Source Code .Data. The following vb. and borders through the use of its properties . Here the DataGridView rows fixed as five rows and other two buttons are there for implementing paging functionalities.net program provides a way to programmatically implement paging in a Windows Datagrid View control. Download Source Code Imports System. columns.The DataGridView class allows customization of cells. While we implement paging we should know the boundaries of the pages to enable the paging in the DatagridView.

ByVal e As System. scrollVal.Object.Fill(pagingDS. ByVal e As System..EventArgs) Handles Button1.Open() pagingAdapter.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.DataSource = pagingDS DataGridView1. "authors_table") connection.Object.Private Sub Button1_Click(ByVal sender As System.5 If scrollVal <= 0 Then scrollVal = 0 End If pagingDS.EventArgs) Handles button2. scrollVal. 5.Clear() pagingAdapter.Initial Catalog=pubs.Object.EventArgs) Handles button3.Click scrollVal = scrollVal . 5.Fill(pagingDS. "authors_table") End Sub Private Sub button3_Click(ByVal sender As System. 5.Clear() pagingAdapter.Fill(pagingDS.Close() DataGridView1. "authors_table") End Sub End Class How to Formatting in DataGridView .Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS. connection) pagingDS = New DataSet() connection.Integrated Security=True" Dim sql As String = "SELECT * FROM authors" Dim connection As New SqlConnection(connectionString) pagingAdapter = New SqlDataAdapter(sql. scrollVal.Click Dim connectionString As String = "Data Source=. ByVal e As System.

The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. and it provides many properties. methods.The DataGridView control is highly configurable and extensible.Data. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications.SqlClient Print Source Code . You can define appearance and formatting styles for individual cells. however. and events to customize its appearance and behavior. The following vb. Typically.net program shows how to implement different ways of cell formatting in a DataGridView control. for cells in specific columns and rows. multiple cells will share particular style characteristics. or for all cells in the control by setting the properties of the DataGridViewCellStyle objects accessed through various DataGridView control properties. Download Source Code Imports System.

Click Dim connectionString As String = "Data Source=.FullRowSelect DataGridView1.Open() dataadapter.Bisque DataGridView1.SelectionForeColor = Color. "Authors_table") connection.DataSource = ds DataGridView1.BackColor = Color. ByVal e As System.SelectionBackColor = Color.Close() DataGridView1.SelectionMode = DataGridViewSelectionMode.WrapMode = DataGridViewTriState.DefaultCellStyle.Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql.RowsDefaultCellStyle.EventArgs) Handles Button1..None DataGridView1.Object.Initial Catalog=pubs.Fill(ds.GridColor = Color.CellBorderStyle = DataGridViewCellBorderStyle.[True] DataGridView1. connection) Dim ds As New DataSet() connection.DefaultCellStyle.AlternatingRowsDefaultCellStyle.Red DataGridView1.BackgroundColor = Color.DefaultCellStyle.Yellow DataGridView1.BackColor = Color.DataMember = "Authors_table" DataGridView1.LightGray DataGridView1.Red DataGridView1.Public Class Form1 Private Sub Button1_Click(ByVal sender As System.AllowUserToResizeColumns = False DataGridView1.Beige End Sub End Class How to DataGridView Template .

the rows are generated automatically. you can set any DataGridViewRow properties.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. With the row template. including DefaultCellStyle.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. but they are based on the row template. The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. which you can set to an instance of your custom row type.Data.Object. ByVal e As System. however.EventArgs) Handles . When displaying external data. The following vb.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.

Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql.Height = 35 row. connection) Dim ds As New DataSet() connection.Bisque row.Click Dim row As DataGridViewRow = Me.MinimumHeight = 20 Dim connectionString As String = "Data Source=.DefaultCellStyle..DataMember = "Authors_table" End Sub End Class How to DataGridView Printing .DataSource = ds DataGridView1.DataGridView1.Button1.Open() dataadapter.BackColor = Color.RowTemplate row. "Authors_table") connection.Close() DataGridView1.Fill(ds.Initial Catalog=pubs.

In order to run this vb.EventArgs) Handles .The DataGridView control provides a customizable table for displaying data. ByVal e As System.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System. Download Source Code Print Source Code Imports System. It gives you number of properties. Unfortunately the DataGridView doesn't have a built in printing functionality .Data. Here in the PrintPage event we create a Bitmap Object and draw the DataGridView to the Bitmap Object.net project you have to drag two buttons . 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. The following picture shows how to drag PrintDocument Object to your project.one for load data and one for print command. So here we do a tricky way to print the content of DataGridView .Object. methods and events to customize its appearance and behavior. and drag a PrintDocument control on your form .

PrintPage Dim bm As New Bitmap(Me.Open() dataadapter.Close() DataGridView1.Click Dim connectionString As String = "Data Source=.DrawImage(bm.Button1. 0.Height) DataGridView1. 0) End Sub End Class How to Export datagridview to Excel The DataGridView control provides a customizable table for displaying data.Height)) e.Object.Click PrintDocument1.Fill(ds.Printing. Me.EventArgs) Handles Button2.DataGridView1. methods. The DataGridView control is highly configurable and extensible. and it provides many properties.DataSource = ds DataGridView1.Width.net source code shows how to Export the content of a datagridview to an Excel file. Me. "Authors_table") connection.Width.DataGridView1. and events to customize its appearance and behavior. Me.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.DataGridView1. The following vb.DrawToBitmap(bm. ByVal e As System.DataGridView1. 0. Displaying data in a tabular format is a task you are likely to perform frequently. .PrintPageEventArgs) Handles PrintDocument1. connection) Dim ds As New DataSet() connection.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.Graphics.Drawing. New Rectangle(0. ByVal e As System.Object.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System..

connection) Dim ds As New DataSet() connection.Value.Object.2 For j = 0 To DataGridView1.DataSource = ds DataGridView1.Application Dim xlWorkBook As Excel.Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql. ByVal e As System.Click Dim connectionString As String = "Data Source=.Object.Interop.Missing.Office.SqlClient Imports Excel = Microsoft.Data.Open() dataadapter..Download Source Code Print Source Code Imports System.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Value Dim i As Int16.Initial Catalog=pubs.Sheets("sheet1") For i = 0 To DataGridView1. ByVal e As System.ToString() Next Next .RowCount .Worksheet Dim misValue As Object = System.Cells(i + 1.Add(misValue) xlWorkSheet = xlWorkBook.Click Dim xlApp As Excel.Fill(ds. j + 1) = DataGridView1(j. j As Int16 xlApp = New Excel.Close() DataGridView1.Workbook Dim xlWorkSheet As Excel.ColumnCount .Reflection.1 xlWorkSheet. i).Workbooks. "Authors_table") connection.EventArgs) Handles Button1.EventArgs) Handles Button2.ApplicationClass xlWorkBook = xlApp.

SaveAs("c:\vb. misValue.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing MessageBox. misValue. Excel. The following vb.InteropServices. misValue. misValue) xlWorkBook.XlSaveAsAccessMode. misValue. misValue.xlExclusive. misValue.net source code shows how to Import data from an Excel file to a DataGridView control .Runtime.Quit() releaseObject(xlWorkSheet) releaseObject(xlWorkBook) releaseObject(xlApp) MessageBox. misValue. misValue. You can use a DataGridView control to display data with or without an underlying data source. misValue) xlApp.Marshal.XlFileFormat.Show("Over") End Sub Private Sub releaseObject(ByVal obj As Object) Try System. Download Source Code Imports System. misValue.SqlClient Public Class Form1 Print Source Code . extensible system for displaying and editing tabular data.net-informations.xlWorkbookNormal.xls".Show("Exception Occured while releasing object " + ex.Close(True. _ Excel.ToString()) Finally GC.Data.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.xlWorkBook.

Data.Close() End Sub End Class Database operations in DatagridView .Click Dim MyConnection As System.OleDbDataAdapter MyConnection = New System.OleDbConnection("provider=Microsoft. "Net-informations.DataSource = DtSet.xls'.Extended Properties=Excel 8.Data.OleDb.4.Data.0.DataSet Dim MyCommand As System.com") DtSet = New System.Data.OleDbDataAdapter("select * from [Sheet1$]".OleDb.DataSet MyCommand.Data.Tables(0) MyConnection.Data.Jet.OleDbConnection Dim DtSet As System.OleDb.EventArgs) Handles Button1.OleDb.Object.Private Sub Button1_Click(ByVal sender As System. MyConnection) MyCommand.0.") MyCommand = New System.net-informations.Fill(DtSet) DataGridView1.Add("Table".TableMappings. ByVal e As System.Data Source='c:\vb.OLEDB.

The following vb. Bound mode is suitable for managing data using automatic interaction with the data store. unbound mode and Virtual mode .net source code illustrate how to connect a DataGridView to a database and addnew/update or delete the database values from DataGridView. One very common use of the DataGridView control is binding to a table in a database.The DataGridView control can display rows of data from a data source. The DataGridView can display data in Bound mode. Download Source Code Imports System.SqlClient Public Class Form1 Dim sCommand As SqlCommand Print Source Code .Data. 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.

Click Dim connectionString As String = "Data Source=. ByVal e As System. ByVal e As System.Update(sTable) End If End Sub .Show("Do you want to delete this row ?".[ReadOnly] = False save_btn. "Delete".Object.Rows. connection) sAdapter = New SqlDataAdapter(sCommand) sBuilder = New SqlCommandBuilder(sAdapter) sDs = New DataSet() sAdapter.Enabled = False DataGridView1. ByVal e As System.EventArgs) Handles new_btn.Fill(sDs.SelectedRows(0).SelectionMode = DataGridViewSelectionMode.RemoveAt(DataGridView1.Enabled = False End Sub Private Sub delete_btn_Click(ByVal sender As System.Object. "Stores") sTable = sDs..Close() DataGridView1.Open() sCommand = New SqlCommand(sql.DataSource = sDs. MessageBoxButtons.FullRowSelect End Sub Private Sub new_btn_Click(ByVal sender As System.Click DataGridView1.EventArgs) Handles delete_btn.Click If MessageBox.YesNo) = DialogResult.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.Initial Catalog=pubs.ReadOnly = True save_btn.Object.Enabled = False delete_btn.EventArgs) Handles load_btn.Tables("Stores") connection.Tables("Stores") DataGridView1.Yes Then DataGridView1.Integrated Security=True" Dim sql As String = "SELECT * FROM Stores" Dim connection As New SqlConnection(connectionString) connection.Enabled = True new_btn.Index) sAdapter.

ByVal e As System.Update(sTable) DataGridView1.Click sAdapter.Object.Enabled = True End Sub End Class .Enabled = True delete_btn.EventArgs) Handles save_btn.Enabled = False new_btn.Private Sub save_btn_Click(ByVal sender As System.[ReadOnly] = True save_btn.

Sign up to vote on this title
UsefulNot useful