ADO.NET
ADO.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
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.
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.
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 .
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 .
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim i As Integer Dim resultValue As Integer i = 100 resultValue = i / 0 MsgBox("The result is " & resultValue) Catch ex As Exception MsgBox("Exception catch here ..") Finally MsgBox("Finally block executed ") End Try End Sub End Class
When you execute this program you will "Exception catch here .." first and then "Finally block executed " . That is when you execute this code , an exception happen and it will go to catch block and then it will go to finally block.
Take a look at the following programs, it will give you a clear picture of Option Explicit. The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The default is Option Explicit On , so we do not need to put it in the source code. VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim someVariable As String someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class
The above program , declare a String variable and assigned a value in it and it displays. Take a look at the following program , it is an example of Option Explicit Of Download Source Code Print Source Code
Option Explicit Off Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class
Here "someVariable" is not declared , because the Option Explicit Of , without any compiler error you can continue the program
Option Strict [On Off] By default Option Strict is Off From the following example you can understand the use of Option Strict. VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum MsgBox(intNum) End Sub End Class
The above program is a normal vb.net program and is in default Option Strict Off . Because its Option Strict Off we can convert the value of Long to an Integer. Take a look at the following program. Download Source Code Print Source Code
Option Strict On Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum
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.
when u execute this program you will get error message like " Arithmetic operation resulted in an overflow " See the program we put an On Error GoTo statement Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo nextstep Dim result As Integer Dim num As Integer num = 100 result = num / 0 nextstep: MsgBox("Control Here") End Sub End Class
When you execute the program you will get the message box "Control Here" . Because the On Error statement redirect the exception to the Label statement.
The Environment Class provides information about, and means to manipulate, the current environment and platform. The Environment Class has a property called OSVersion which returns an object of type OperatingSystem.
Dim _os As OperatingSystem _os = Environment.OSVersion
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim _os As OperatingSystem _os = Environment.OSVersion MsgBox(_os.VersionString.ToString) End Sub End Class
The Environment Class provides information about, and means to manipulate, the current environment and platform. The Environment Class has a property called OSVersion which returns an object of type OperatingSystem.
Dim _os As OperatingSystem _os = Environment.OSVersion
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim _os As OperatingSystem _os = Environment.OSVersion MsgBox(_os.VersionString.ToString) End Sub End Class
If [your condition here] Your code here Else Your code Here End If
If the contition is TRUE then the control goes to between IF and Else block , that is the program will execute the code between IF and ELSE statements. If the contition is FLASE then the control goes to between ELSE and END IF block , that is the program will execute the code between ELSE and END IF statements. If you want o check more than one condition at the same time , you can use ElseIf .
If [your condition here] Your code here ElseIf [your condition here] Your code here ElseIf [your condition here] Your code here Else Your code Here End If
Just take a real-time example - When we want to analyze a mark lists we have to apply some conditions for grading students depends on the marks. Following are the garding rule of the mark list: 1) If the marks is greater than 80 then the student get higher first class 2) If the marks less than 80 and greater than 60 then the student get first class 3) If the marks less than 60 and greater than 40 then the student get second class
4) The last condition is , if the marks less than 40 then the student fail. Now here implementing these conditions in a VB.NET program.
1. 2. 3. 4. 5. 6. 7. 8. 9. If totalMarks >= 80 Then MsgBox("Got Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Got First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If
Line 1 : Checking the total marks greaterthan or equal to 80 Line 2 : If total marks greater than 80 show message - "Got Higher First Class " Line 3 : Checking the total marks greaterthan or equal to 60 Line 4 : If total marks greater than 60 show message - "Got First Class " Line 5 : Checking the total marks greaterthan or equal to 40 Line 6 : If total marks greater than 40 show message - "Just pass only" Line 7 : If those three conditions failed program go to the next coding block Line 8 : If all fail shows message "Failed" Line 9 : Ending the condition block VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim totalMarks As Integer totalMarks = 59 If totalMarks >= 80 Then MsgBox("Gor Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Gor First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If End Sub End Class
In this example the total marks is 59 , when you execute this program you will get in messagebox "Just Pass Only" If you want to check a condition within condition you can use nested if statements
If [your condition here] If [your condition here] Your code here Else Your code Here End If Else Your code Here End If
Also you can write IF ELSE Statements in a single line If [your condition here] [Code] Else [code] Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim totalMarks As Integer totalMarks = 39 If totalMarks >= 50 Then MsgBox("passed ") Else MsgBox("Failed ") End Sub End Class
When you execute this program you will get in messagebox "Failed "
var : The counter for the loop to repeat the steps. starValue : The starting value assign to counter variable . endValue : When the counter variable reach end value the Loop will stop .
loopBody : The source code between loop body Lets take a simple real time example , If you want to show a messagebox 5 times and each time you want to see how many times the message box shows.
1. 2. 3. 4. 5. startVal=1 endVal = 5 For var = startVal To endVal show message Next var
Line 1: Loop starts value from 1 Line 2: Loop will end when it reach 5 Line 3: Assign the starting value to var and inform to stop when the var reach endVal Line 4: Execute the loop body Line 5: Taking next step , if the counter not reach the endVal VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " & var & " Times ") Next var End Sub
End Class
When you execute this program , It will show messagebox five time and each time it shows the counter value. If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop body.
For var=startValue To endValue [Step] [loopBody] Contition [Exit For] Next [var]
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " var " Times ") If var = 3 Then Exit For End If Next var End Sub End Class
When you execute the above source code , the program shows the message box only three times .
Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you have to repeat a task till you reach a condition, in these situations you can use loop statements to achieve your desired results. FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly used loops in Visual Basic.NET 2005 ( VB.NET 2005) . For Each Loop FOR EACH Loop usually using when you are in a situation to execute every single element or item in a group (like every single element in an Array, or every single files in a folder or , every character in a String ) , in these type of situation you can use For Each loop.
For Each [Item] In [Group] [loopBody] Next [Item]
Item : The Item in the group Group : The group containing items LoopBody : The code you want to execute within For Each Loop Let's take a real time example , if you want to display the each character in the website name "HTTP://NET-INFORMATIONS.COM" , it is convenient to use For Each Loop.
1. siteName = "HTTP://NET-INFORMATIONS.COM" 2. For Each singleChar In siteName 3. MsgBox(singleChar) 4. Next
Line 2: This line is extracting the single item from the group Line 3: Loop body Line 4: Taking the next step Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim siteName As String Dim singleChar As Char siteName = "HTTP://NET-INFORMATIONS.COM" For Each singleChar In siteName MsgBox(singleChar) Next End Sub End Class
When you execute this program you will get each character of the string in Messagebox.
Line 1: Counter start from 1 Line 2: While loop checking the counter if it is less than or equal to 10 Line 3: Each time the Loop execute the message and show Line 4: Counter increment the value of 1 each time the loop execute Line 5: End of the While End While Loop body Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim counter As Integer counter = 1 While (counter <= 10) MsgBox("Counter Now is : " counter) counter = counter + 1 End While End Sub
End Class
When you execute the program 10 times the message shows with counter and exit from the While .. End While loop.
The following VB.NET program shows, how to create a custom exception class and how it is using in the program. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim i As Integer
Dim j As Integer Dim k As Integer j = 10 k = 0 i = j / k Catch ex As Exception Throw (New MyCustomException("You can not divide a number by zeo")) End Try End Sub End Class Public Class MyCustomException Inherits System.ApplicationException Public Sub New(ByVal message As String) MyBase.New(message) MsgBox(message) End Sub End Class
An array that uses more than one index or subscript is called multidimensional. A dimension is a direction in which you can vary the specification of an arrays elements. Some arrays have two dimensions, therefore, such an array uses two indexes. The following example declares a variable to hold a twodimensional array of office counts, for buildings 0 through 40 and floors 0 through 5.
Dim offices(40, 5) As Byte
The following VB.NET program shows a simple example of how to insert values in a two dimensional array and retrieve the values from two dimensional array. Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i, j As Integer Dim strArr(1, 2) As String strArr(0, 0) = "First (0,0)" strArr(0, 1) = "Second (0,1)" strArr(1, 0) = "Third (1,0)" strArr(1, 1) = "Fourth (1,1)" For i = 0 To strArr.GetUpperBound(0) For j = 0 To strArr.GetUpperBound(0) MsgBox(strArr(i, j)) Next Next End Sub End Class
VB.NET CONNECTIONS
VB.NET Collections
Visual Basic .NET Collections are data structures that holds data in different ways for flexible operations . The important datastructres in the Colletions are ArrayList , HashTable , Stack and Queue etc. In the following chapters you can see how to manage these datastructures in your visual basic.net (vb.net) programs.
ArrayList is one of the most flixible data structure from VB.NET Collections. ArrayList contains a simple list of values and very easily we can add , insert , delete , view etc.. to do with ArrayList. It is very flexible becuse we can add without any size information , that is it grow dynamically and also shrink .
Important functions in ArrayList
Add : Add an Item in an ArrayList Insert : Insert an Item in a specified position in an ArrayList Remove : Remove an Item from ArrayList RemoveAt: remeove an item from a specified position Sort : Sort Items in an ArrayList How to add an Item in an ArrayList ? Syntax : ArrayList.add(Item) Item : The Item to be add the ArrayList Dim ItemList As New ArrayList() ItemList.Add("Item4") How to Insert an Item in an ArrayList ? Syntax : ArrayList.insert(index,item) index : The position of the item in an ArrayList Item : The Item to be add the ArrayList
ItemList.Insert(3, "item6") How to remove an item from arrayList ? Syntax : ArrayList.Remove(item) Item : The Item to be add the ArrayList ItemList.Remove("item2") How to remove an item in a specified position from an ArrayList ? Syntax : ArrayList.RemoveAt(index) index : the position of an item to remove from an ArrayList ItemList.RemoveAt(2) How to sort ArrayList ? Syntax : ArrayListSort() The following VB.NET source code shows some function in ArrayList
Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim ItemList As New ArrayList() ItemList.Add("Item4") ItemList.Add("Item5") ItemList.Add("Item2") ItemList.Add("Item1") ItemList.Add("Item3")
MsgBox("Shows Added Items") For i = 0 To ItemList.Count MsgBox(ItemList.Item(i)) Next 'insert an item ItemList.Insert(3, "Item6") 'sort itemms in an arraylist ItemList.Sort() 'remove an item ItemList.Remove("Item1") 'remove item from a specified ItemList.RemoveAt(3) MsgBox("Shows final Items the For i = 0 To ItemList.Count MsgBox(ItemList.Item(i)) Next End Sub End Class
index ArrayList") 1
When you execute this program , at first add five items in the arraylist and displays. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing items.
Value : The value of corrosponding key ContainsKey : Check if a specified key exist or not Synatx : HashTable.ContainsKey(key) Key : The Key value for search in HahTable ContainsValue : Check the specified Value exist in HashTable Synatx : HashTable.ContainsValue(Value) Value : Search the specified Value in HashTable Remove : Remove the specified Key and corrosponding Value Syntax : HashTable.Remove(Key) Key : The argument key of deleting pairs The following source code shows all important operations in a HashTable Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim weeks As New Hashtable Dim day As DictionaryEntry weeks.Add("1", "Sun") weeks.Add("2", "Mon") weeks.Add("3", "Tue") weeks.Add("4", "Wed") weeks.Add("5", "Thu") weeks.Add("6", "Fri") weeks.Add("7", "Sat")
'Display a single Item MsgBox(weeks.Item("5")) 'Search an Item If weeks.ContainsValue("Tue") Then MsgBox("Find") Else MsgBox("Not find") End If 'remove an Item weeks.Remove("3") 'Display all key value pairs For Each day In weeks MsgBox(day.Key " -- " day.Value) Next End Sub End Class
When you execute this program it add seven weekdays in the hashtable and display the item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from HashTable. Finaly it displays all item exist in the HashTable.
Push : Add (Push) an item in the stack datastructure Syntax : Stack.Push(Object) Object : The item to be inserted.
Pop : Pop return the item last Item to insert in stack Syntax : Stack.Pop() Return : The last object in the Stack Contains : Check the object contains in the stack Syntax : Stack.Contains(Object) Object : The specified Object to be seach The following VB.NET Source code shows some of commonly used functions :
Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stackTable As New Stack stackTable.Push("Sun") stackTable.Push("Mon") stackTable.Push("Tue") stackTable.Push("Wed") stackTable.Push("Thu") stackTable.Push("Fri") stackTable.Push("Sat") If stackTable.Contains("Wed") Then MsgBox(stackTable.Pop()) Else MsgBox("not exist") End If End Sub End Class
When you execute this program add seven items in the stack . Then its checks the item "Wed" exist in the Stack. If the item exist in the Stack , it Pop the last item from Stack , else it shows the msg "Not Exist"
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 :
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.
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 .
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.
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.
Dim str As String = "http://vb.net-informations.com" Dim encod As New System.Text.UTF8Encoding Dim byteData() As Byte = encod.GetBytes(str) Dim oFileStream As System.IO.FileStream oFileStream = New System.IO.FileStream("c:\bytes.txt", System.IO.FileMode.Create) oFileStream.Write(byteData, 0, byteData.Length) oFileStream.Close() End Sub End Class
An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The default number of array elements is set to zero and the reference element is set to null. The elements of an array can be of any type, including an array type. The following VB.NET source code shows how to write the array content into a text file. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim months(11) As String months(0) = "Jan" months(1) = "Feb" months(2) = "Mar" months(3) = "Apr" months(4) = "May" months(5) = "Jun"
months(6) = "Jul" months(7) = "Aug" months(8) = "Sep" months(9) = "Oct" months(10) = "Nov" months(11) = "Dec" System.IO.File.WriteAllLines("c:\file.txt", months) End Sub End Class
For ex: "This is a Test".Length() returns 14. Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "This is a Test" MsgBox(str.Length()) End Sub End Class
When you execute this source code you will get 17 in the messagebox.
System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this instance System.ArgumentNullException : If the argument is null. For ex: "This is Test".Insert(8,"Insert ") returns "This is Insert Test" Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "This is VB.NET Test" Dim insStr As String = "Insert " Dim strRes As String = str.Insert(15, insStr) MsgBox(strRes) End Sub End Class
When you execute this program you will get the message box showing "This is VB.NET Insert Test"
Integer - If the parameter String occurred as a substring in the specified String it returns position of the first character of the substring . If it does not occur as a substring, -1 is returned. Exceptions: System.ArgumentNullException: If the Argument is null. For ex: "This is a test".IndexOf("Test") returns 10 "This is a test".IndexOf("vb") returns -1 Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" MsgBox(str.IndexOf("BOOKS")) End Sub End Class
When you execute this program you will get the number 14 in the message box. That means the substring "BOOKS" occurred and start in the position 14.
System.Format(ByVal format As String, ByVal arg0 As Object) As String Parameters: String format : The format String The format String Syntax is like {indexNumber:formatCharacter} Object arg0 : The object to be formatted. Returns: String : The formatted String Exceptions: System.ArgumentNullException : The format String is null. System.FormatException : The format item in format is invalid. The number indicating an argument to format is less than zero, or greater than or equal to the number of specified objects to format. For ex : Currency : String.Format("{0:c}", 10) will return $10.00 The currency symbol ($) displayed depends on the global locale settings. Date : String.Format("Today's date is {0:D}", DateTime.Now)
You will get Today's date like : 01 January 2005 Time : String.Format("The current time is {0:T}", DateTime.Now) You will get Current Time Like : 10:10:12
Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim dNum As Double dNum = 32.123456789 MsgBox("Formated String " & String.Format("{0:n4}", dNum)) End Sub End Class
When you run this source code yo will get "Formated String 32.1234"
Boolean : Yes/No It return the values of the two String Objects are same For ex : Str1 = "Equals()" Str2 = "Equals()" String.Equals(Str1,Str2) returns True String.Equals(Str1.ToLower,Str2) returns False Because the String Objects values are different Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "Equals" Dim str2 As String = "Equals" If String.Equals(str1, str2) Then MsgBox("Strings are Equal() ") Else MsgBox("Strings are not Equal() ") End If End Sub End Class
When you run this program you will get message "Strings are Equal() "
VB.NET String CopyTo method Copies a specified number of characters from a specified position in this instance to a specified position in an array of characters. System.String.CopyTo(ByVal sourceIndex As Integer, ByVal destination() As Char, ByVal destinationIndex As Integer, ByVal count As Integer) Parameters: Integer sourceIndex : The starting position of the source String Char destination() : The character Array Integer destinationIndex : Array element in the destination Integer count : The number of characters to destination Exceptions: System.ArgumentNullException : If the destination is null System.ArgumentOutOfRangeException : Source Index, DestinationIndes or Count is a -ve value Count is greater than the length of the substring from startIndex to the end of this instance count is greater than the length of the subarray from destinationIndex to the end of destination Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "CopyTo() sample" Dim chrs(5) As Char
str1.CopyTo(0, chrs, 0, 6) MsgBox(chrs(0) + chrs(1) + chrs(2) + chrs(3) + chrs(4) + chrs(5)) End Sub End Class
When you run this Source code you will get CopyTo in MessageBox
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "VB.NET Copy() test" str2 = String.Copy(str1)
When you run this source code you will get same content of str1 in str2
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.Contains("TOP") = True Then MsgBox("The string Contains() 'TOP' ") Else MsgBox("The String does not Contains() 'TOP'") End If End Sub End Class
When you run the program you will get the MessageBox with message "The string Contains() 'TOP' "
Integer : returns less than zero, zero or greater than zero. Less than zero : str1 is less than str2 zero : str1 is equal to str2 Greater than zero : str1 is grater than str2 Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "vb.net" str2 = "VB.NET" Dim result As Integer result = String.Compare(str1, str2) MsgBox(result) result = String.Compare(str1, str2, True) MsgBox(result) End Sub End Class
When you run this program first u get -1 in message box and then 0
Returns: Object : Return the instance of the String Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "Clone() Test" Dim clonedString As String clonedString = str.Clone() MsgBox(clonedString) End Sub End Class
When you run this program you ill get the same content of the first string "Clone() Test"
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "Clone() Test" Dim clonedString As String clonedString = str.Clone()
When you run this program you ill get the same content of the first string "Clone() Test"
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String Dim retString As String str = "This is substring test" retString = str.Substring(8, 9) MsgBox(retString) End Sub End Class
When you execute this program , its will display "subtring" in the messagebox.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ")
When you execute this programme , you will get "vb.net" "split" "test" in separate messagebox.
System.ArgumentNullException : If the argument is null Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.EndsWith("BOOKS") = True Then MsgBox("The String EndsWith 'BOOKS' ") Else MsgBox("The String does not EndsWith 'BOOKS'") End If End Sub End Class
When you execute the program you will get a message box like "The String EndsWith 'BOOKS' "
Returns: String : A new String retrun with str1 Concat with str2 Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "Concat() " str2 = "Test" MsgBox(String.Concat(str1, str2)) End Sub End Class
When you run this source code you will get "Concat() Test " in message box.
A neutral culture is specified by only the two-letter lowercase language code. For example, "fr" specifies the neutral culture for French, and "de" specifies the neutral culture for German.
Dim cultureInfo As New System.Globalization.CultureInfo("en-US")
The String class indirectly uses this class to obtain information about the default culture. The follwoing VB.NET source code shows how to convert a string to Title Case.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim _str As String Dim cultureInfo As New System.Globalization.CultureInfo("en-US") _str = cultureInfo.TextInfo.ToTitleCase("make first letter capital") MsgBox(_str) End Sub End Class
StringReader Class Implements a TextReader that reads from a string. StringReader.ReadLine Method Reads a line from the underlying string.
Dim message As String Dim stringReader As New StringReader(String)
The next line from the underlying string, or Nothing if the end of the underlying string is reached. The following program shows how to use StringWriter and StringReader Classes in VB.NET.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stringWriter As New StringWriter() stringWriter.WriteLine("net-informations.com") stringWriter.WriteLine("vb.net-informations.com") stringWriter.WriteLine("csharp.net-informations.com") MsgBox(stringWriter.ToString) Dim singleLine As String Dim message As String Dim stringReader As New StringReader(stringWriter.ToString) While True singleLine = stringReader.ReadLine If singleLine Is Nothing Then Exit While Else message = message & singleLine & Environment.NewLine End If End While MsgBox(message) End Sub End Class
Create a new Crystal Reports for Product table from the above database crystalDB. The Product Table has three fields (Product_id,Product_name,Product_price) and we are showing the whole table data in the Crystal Reports. From main menu in Visual Studio select PROJECT-->Add New Item . Then Add New Item dialogue will appear and select Crystal Reports from the dialogue box.
Accept the default settings and click OK. Next step is to select the appropriate connection to your database. Here we are going to select OLEDB connection for SQL Server Select OLE DB (ADO) from Create New Connection .
Next screen is the SQL Server authentication screen . Select your Sql Server name , enter userid , password and select your Database Name . Click next , Then the screen shows OLE DB Property values , leave it as it is , and click finish. Then you will get your Server name under OLEDB Connection from there select database name (Crystaldb) and click the tables , then you can see all your tables from your database. From the tables list select Product table to the right side list .
Click Next Button Select all fields from Product table to the right side list .
Click Finish Button. Then you can see the Crystal Reports designer window . You can arrange the design according your requirements. Your screen look like the following picture.
Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form.
Select Form's source code view and put the code on top Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Reports is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. After you run the source code you will get the report like this.
Create a DataBase "crystaldb" In the crystaldb database , create three tables OrderMaster , OrderDetails , Product . OrderMaster OrderMaster_id OrderMaster_date OrderMaster_customer OrderMaster_createduser OrderDetails OrderDetails_id OrderDetails_masterid OrderDetails_productid OrderDetails_qty Product Product_id Product_name Product_price
SQL command for creation tables are follows : CREATE TABLE [dbo].[OrderMaster] ( [OrderMaster_id] [int] NOT NULL , [OrderMaster_date] [datetime] NULL , [OrderMaster_customername] [varchar] (50), [OrderMaster_createduser] [varchar] (50) ) ON [PRIMARY]
CREATE TABLE [dbo].[OrderDetails] ( [OrderDetails_id] [int] NOT NULL , [OrderDetails_masterid] [int] NULL , [OrderDetails_productid] [int] NULL , [OrderDetails_qty] [int] NULL ) ON [PRIMARY] CREATE TABLE [dbo].[Product] ( [Product_id] [int] NOT NULL , [Product_name] [varchar] (50) , [Product_price] [numeric](18, 0) NULL ) ON [PRIMARY] Enter data to the tables : Order Master Table Data
From main menu in Visual Studio select PROJECT-->Add New Item . Then Add New Item dialogue will appear and select Crystal Reports from the dialogue box.
Accept the default settings and click OK. Next step is to select the appropriate connection to your database. Here we are going to select OLEDB connection for SQL Server Select OLE DB (ADO) from Create New Connection .
Next screen is the SQL Server authentication screen . Select your Sql Server name , enter userid , password and select your Database Name . Click next , Then the screen shows OLE DB Property values , leave it as it is , and click finish. Then you will get your Server name under OLEDB Connection from there select database name (Crystaldb) and click the tables , then you can see all your tables from your database.
Select all table from the table list to right side list box, because we are creating report from three tables ( OrderMaster, OrderDetails, Product) .
The next step is to make relation between these selected tables. Here we are connecting the related fields from each table. For that we arrange the tables in visible area in the list (this is not necessary ) and select the field we are going to make relation and drag to the related field of the other table. After made the relation the screen is look like the following picture .
Next step is to select the fields from the tables . Here we are selecting only Customername , orderdate from ordermastertable , Productname from product table and quantity from order details.
Click the Finish button because now we are not using other functionalities of this wizard. After that you will get the Crystal Reports designer window . You can arrange the fields in the designer window according to your requirement to view the report . For rearranging you can drag the field object in the screen . For editing right click the field object and select Edit Text Object. The following picture shows the sample of designer window after rearrange the field.
Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form.
Select Form's source code view and put the code on top Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. After you run the source code you will get the report like this.
Here we connected three tables related field and get the result . If you have any comments please contact the email address in our contact page.
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Here we are passing a String parameter from vb.net to Crystal Reports . For that , from vb.net program we pass a customer name as parameter and show all the order of that customer to the Crystal Reports. In the previous tutorial we saw how to generate a Crystal Reports from multiple tables. Here is the continuation of that tutorial , the only different is that we are passing a Customer Name as a String parameter and get the report of that particular Customer only . Before starting to this tutorial just take a look at the previous tutorial ( Crystal Report from multiple tables ). In the previous section we are getting the report of all orders from all customers , that is the all order placed by all customers , here is only one customer. Hope you went through previous tutorial , if not click here ( Crystal Report from multiple tables ). Next step is to create a string parameter in Crystal report. Select the Field Explorer from CrystalReport Menu.
Then you can see Field Explorer in the Left hand side.
Fill the appropriate name for Name and Promting text fields
After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD .
Then you can see the record Selection Formula Editor. This for entering the selection formula. For that you have to select the fields from above fields and make the formula . First you have to select OrderMaster.OrderMaster_customername from Report Field and select the comparison operator and select the parameter field. Double click each field then it will be selected. Form the following picture you can understand the selection fields.
After the creation of selection formula close that screen . Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and CrystalReportViewer control to your form.
Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = TextBox1.Text crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Item("Customername") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Now you can run the program . Enter a Customer Name(enter any existing customer from Ordermaster table) and click the button , then your report is look like the following picture.
In the previous tutorial , we saw passing a string parameter to Crystal Reports from VB.NET and get the result. This is very similar to that tutorial , so here showing only the change information part only. So please take a look at the complete part of passing a string parameter to Crystal Reports from VB.NET. When we pass an Integer parameter , we have to create a new Integer parameter in the Parameter Fields of Field Explorer. Then we will get the following screen and fill the fields like in the picture .
After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD . Then you can see the record Selection Formula Editor. This for entering the selection formula. For that you have to select the fields from above lists and make the formula .
Here we made the formula like select the records from Product table whose value is greater than the input value. For that first we select the table field that is Product_price from Product table and then we select the comparison operator and finally we select our Parameter we created earlier. Double click each field then it will automatically selected
After the creation of selection formula close that screen . Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Reports Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and CrystalReportViewer control to your form. Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = Convert.ToInt32(TextBox1.Text) crParameterFieldDefinitions = _ cryRpt.DataDefinition.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Item("Price") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Now you can run the program . Enter any price , then you can see the report of the Product list whose price is greater than or equal to the entered price.
Here we got the result of Product list whose price is grater than 50.
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are passing a date variable to Crystal Reports from VB.NET. In the previous tutorials , we saw passing a string parameter to Crystal Reports , integer parameter to Crystal report from VB.NET and get the result. This tutorial is very similar to the above two tutorials , so please take look into the two tutorials before we start this one. When we pass a Date parameter, we have to create a new date parameter in the Parameter Fields of Field Explorer. Then we will get the following screen and fill the fields like in the picture .
After creating the parameter field , we have to create the selection formula for the Crystal Reports . For creating selection formula , Right click on Crystal Reports designer window , select REPORT -> SELECTION FORMULA -> RECORD .
Then you can see the record Selection Formula Editor. This for entering the selection formula. For that you have to select the fields from above lists and make the formula . Here we are making the formula like , select all records details from the tables whose order date is greater than the input date parameter. For doing this you have to select Ordermaster.orderdate , comparison operator and parameter date field from selection list of Formula Editor and make the formula.
After the creation of selection formula close that screen . Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET through Crystal Report Viewer control . Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and CrystalReportViewer control to your form.
Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") Dim Dim Dim Dim crParameterFieldDefinitions As ParameterFieldDefinitions crParameterFieldDefinition As ParameterFieldDefinition crParameterValues As New ParameterValues crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = TextBox1.Text crParameterFieldDefinitions = _ cryRpt.DataDefinition.ParameterFields crParameterFieldDefinition = _ crParameterFieldDefinitions.Item("Orderdate") crParameterValues = crParameterFieldDefinition.CurrentValues crParameterValues.Clear() crParameterValues.Add(crParameterDiscreteValue) crParameterFieldDefinition.ApplyCurrentValues(crParameterValues) CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Now you can run the program . Enter any date , then you can see the report whose order date is greater than or equal to the entered date.
Here we got the result of orders whose date is greater than the entered date
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this section we are passing User ID , Password , Server Name and Database Name dynamically to Crystal Reports from vb.net . SITUATIONS : In many situations this is useful , for example if you develop a database project in a test server and later you have to migrate it , in such situations you have to give these information dynamically to Crystal Reports. In this program we are using our earlier program and pass the values dynamically to Crystal Reports. Before we start this section take a look at the step by step Crystal Report in VB.NET . In the step by step Crystal Report we created a report selecting all data from the Product table . There is no chance to change the server on runtime in that case because it is a static report . Here we are passing Server Name , UserID and Password dynamically to the Crystal Reports. Here we use Crystal Reports ConnectionInfo . Dim crConnectionInfo As New ConnectionInfo , and pass these arguments to ConnectionInfo Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Put the following source code in the button click event Download Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument Dim crtableLogoninfos As New TableLogOnInfos Dim crtableLogoninfo As New TableLogOnInfo Dim crConnectionInfo As New ConnectionInfo Dim CrTables As Tables Dim CrTable As Table cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") With crConnectionInfo .ServerName = "YOUR SERVER NAME" .DatabaseName = "YOUR DATABASE NAME" .UserID = "YOUR DATABASE USERNAME" .Password = "YOUR DATABASE PASSWORD" End With CrTables = cryRpt.Database.Tables For Each CrTable In CrTables crtableLogoninfo = CrTable.LogOnInfo crtableLogoninfo.ConnectionInfo = crConnectionInfo CrTable.ApplyLogOnInfo(crtableLogoninfo) Next CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. You have to replace the source code values of "YOUR SERVER NAME" , "YOUR DATABASE NAME" , "YOUR DATABASE USERNAME" , "YOUR DATABASE PASSWORD" with your correct values .
When you run this program you will get the following screen.
If you have a Crystal Reports with Qty and Price , you need an additional field in your Crystal Reports for the Total of QTY X PRICE . In this situation you have to use the Formula Field in Crystal Reports. In this tutorial we are showing the all orders with qty and price and the total of each row , that means each in each row we are showing the total of qty and price. Before starting this tutorial. Create a new Crystal Reports with fields CustomerName , Order Date , Product Name and Product Price . If you do not know how to create this report , just look the previous tutorial Crystal Report from multiple tables . In that report selecting only four fields , here we need one more field Prodcut->Price . After you create the Crystal Reports you screen is look like the following picture :
Next is to create the a Formula Field for showing the total of Qty and Price . Right Click Formula Field in the Field Explorer and click New. Then you will get an Input Message Box , type Total in textbox and click Use Editor
Now you can see Formula Editor screen . Now you can enter which formula you want . Here we want the result of Qty X Price . For that we select OrderDetails.Qty , the multiplication operator and Product.Price . Double click each field for selection.
Now you can see Total Under the Formula Field . Drag the field in to the Crystal Reports where ever you want .
Now the designing part is over . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub
End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the following screen.
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are taking the sum of field value of Total . This is the continuation of the previous tutorial Crystal Report Formula Field . So before we start this tutorial , take a look at the previous tutorial Crystal Report Formula Field. Here we are taking the grand total of the Total field . The Total field is a Formula field is the result of qty X price . In the Crystal Reports designer view right click on the Report Footer , just below the Total field and select Insert -> Summary .
Then you will get a screen , select the Total from the combo box and Sum from next Combo Box , and summary location Grand Total (Report Footer) . Click Ok button
Now you can see @Total is just below the Total field in the report Footer.
Now the designing part is over . Select the default form (Form1.vb) you created in VB.NET and drag a button and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click event Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the following screen.
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions() CrDiskFileDestinationOptions.DiskFileName = _ "c:\crystalExport.pdf" CrExportOptions = cryRpt.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.PortableDocFormat .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With cryRpt.Export() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the PDF file (crystalExport.pdf) in your computer's C:
Exporting from Crystal Reports to Excel format , we are using Crystal Reports CrExportOptions . Also we have to set ExcelFormatOptions and ExportFormatType.Excel . In the following example you can see how to export a Crystal Reports as a Excel format file. All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we are using our earlier program step by step Crystal Report pull data from database to Crystal Reports . Before we start this section take a look at the step by step Crystal Report in VB.NET . In the step by step Crystal Report we pull all data from Product table , here now we are exporting that data to a Excel format file. Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1, Button2 ) and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Put the following source code in the button click events Download Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Dim cryRpt As New ReportDocument Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New ExcelFormatOptions CrDiskFileDestinationOptions.DiskFileName = _ "c:\crystalExport.xls" CrExportOptions = cryRpt.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.Excel .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With cryRpt.Export() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. When you run this program you will get the Excel file (crystalExport.xls) in your computer's C:
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . In this tutorial we use the tutorial Export Crystal Report to PDF file . So before we start this section please take a look at the tutorial Export Crystal Report to PDF file After export the Crystal Reports as a PDF file , the next step is to email that file . For that here we are using System.Web.Mail . We have to provide the necessary information to configuring SmtpMail client and send the exported file as attachment . Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1, Button2 ) and CrystalReportViewer control to your form. Select Form's source code view and import the following : Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Web.Mail Put the following source code in the button click events Download Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Web.Mail Public Class Form1 Dim cryRpt As New ReportDocument Dim pdfFile As String = "c:\ProductReport1.pdf" Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Try Dim CrExportOptions As ExportOptions Dim CrDiskFileDestinationOptions As New _ DiskFileDestinationOptions() Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions CrDiskFileDestinationOptions.DiskFileName = pdfFile CrExportOptions = cryRpt.ExportOptions With CrExportOptions .ExportDestinationType = ExportDestinationType.DiskFile .ExportFormatType = ExportFormatType.PortableDocFormat .DestinationOptions = CrDiskFileDestinationOptions .FormatOptions = CrFormatTypeOptions End With cryRpt.Export() Catch ex As Exception MsgBox(ex.ToString) End Try sendMail() End Sub Private Sub sendMail() Try Dim Smtp As SmtpMail SmtpMail.SmtpServer.Insert(0, "your hostname") Dim Msg As MailMessage = New MailMessage Msg.To = "to address here" Msg.From = "from address here" Msg.Subject = "Crystal Report Attachment " Msg.Body = "Crystal Report Attachment " Msg.Attachments.Add(New MailAttachment(pdfFile)) Smtp.Send(Msg) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
NOTES: cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here. Before you run this programme , you have to provide the necessary SMTP informations , that is your HOSTNAME , FROM ADDRESS and TO ADDRESS to the SMTP client.
Accept the default name DataSet1.xsd . Create a data table for DataSet1.xsd . Select DataSet1.xsd from Solution Explorer and right click . Select datatable from the menu. Then you will get a datatable in the Datast . Right click the datatable and select Add-Column .
Here we are making a two column Crystal Reports , so we need two column in the data table . Add and ID column and Name column in the Data Table.
Now the dataset part is over . Next step is to create a Crystal Reports from this Dataset . Before going to make Crystal Reports design please take a look at step by step Crystal Report for easy creation of Crystal Reports. Select a new Crystal Reports from Add New Item menu and accept the default settings. The next screen is to select appropriate data source . There you can find the Datatable1 from Project data - ADO.NET Datasets , and select Datatable1 to the right side.
Click Next button and select ID and Name from the datatable1 to right side and click finish.
Now the Crystal Reports designer part is over . Next part is to create data for the Crystal Reports . For that we have to create a Data Table through programmatically and add data to dataset1. Select the default form (Form1.vb) you created in VB.NET and drag one button and CrystalReportViewer control to your form. Put the following source code in the button click events Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet1 Dim t As DataTable = ds.Tables.Add("Items") t.Columns.Add("id", Type.GetType("System.Int32")) t.Columns.Add("Item", Type.GetType("System.String")) Dim r As DataRow Dim i As Integer For i = 0 To 9 r = t.NewRow() r("id") = i r("Item") = "Item" & i t.Rows.Add(r) Next Dim objRpt As New CrystalReport1 objRpt.SetDataSource(ds.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1.Refresh() End Sub End Class
The basics of Crystal Reports creation you can find in the previous section of this tutorial , before we start this tutorial you can take a look at the step by step Crystal Report. Generating a Strongly Typed DataSet In the previous section you can see a detailed tutorial about to create a strongly typed datset and its Crystal Reports design . After create the dataset and Crystal Reports design you should create a connection object and fetch the data from database. Select the default form (Form1.vb) you created in VB.NET and drag one button and CrystalReportViewer control to your form. Put the following source code in the button click events Download Source Code Print Source Code
Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet1 Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=servername; _ initial catalog=crystaldb;user id=username;password=password;" cnn = New SqlConnection(connectionString) cnn.Open() sql = "SELECT Product_id,Product_name,Product_price FROM Product" Dim dscmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet1 dscmd.Fill(ds, "Product") MsgBox(ds.Tables(1).Rows.Count) cnn.Close()
Dim objRpt As New CrystalReport1 objRpt.SetDataSource(ds.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1.Refresh() End Sub End Class
NOTE : You have to provide the necessary databse information to Connection String.
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Create a new VB.NET project and add a Strongly Typed Dataset . Before creating a Strongly Typed take a look at the detailed tutorial of create a strongly typed datset and add five column in the Datatable. Here we are limiting as five column , but you can add any number of column according to your requirements.
Next step is to create a Crystal Reports design from the Strongly Typed dataset.
Select the default form(Form1.vb) and add a TextBox , Button and Crystal Reports Viewer . Here we are going to pass the SQl statements to Crystal Reports at runtime . For that we parsing the SQL statement before we passing it to Crystal Reports. So we create a function for parsing SQL statements. Public Function procesSQL() As String Put the following vb.net source code in your form and run the program .
Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Data Public Class Form1 Dim objRpt As New CrystalReport1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim cnn As SqlConnection Dim connectionString As String Dim sql As String connectionString = "data source=SERVERNAME; _ initial catalog=crystaldb;user id=sa;password=PASSWORD;" cnn = New SqlConnection(connectionString) cnn.Open() sql = procesSQL() Dim dscmd As New SqlDataAdapter(sql, cnn) Dim ds As New DataSet1 dscmd.Fill(ds, "Product") objRpt.SetDataSource(ds.Tables(1)) CrystalReportViewer1.ReportSource = objRpt CrystalReportViewer1.Refresh() End Sub Public Function procesSQL() As String Dim sql As String Dim inSql As String Dim firstPart As String Dim lastPart As String Dim selectStart As Integer Dim fromStart As Integer Dim fields As String() Dim i As Integer Dim MyText As TextObject inSql = TextBox1.Text inSql = inSql.ToUpper selectStart = inSql.IndexOf("SELECT")
fromStart = inSql.IndexOf("FROM") selectStart = selectStart + 6 firstPart = inSql.Substring(selectStart, (fromStart - selectStart)) lastPart = inSql.Substring(fromStart, inSql.Length - fromStart) fields = firstPart.Split(",") firstPart = "" For i = 0 To fields.Length - 1 If i > 0 Then firstPart = firstPart & " , " _ & fields(i).ToString() & " AS COLUMN" & i + 1 MyText = CType(objRpt.ReportDefinition.ReportObjects("Text" _ & i + 1), TextObject) MyText.Text = fields(i).ToString() Else firstPart = firstPart & fields(i).ToString() & _ " AS COLUMN" & i + 1 MyText = CType(objRpt.ReportDefinition.ReportObjects("Text" & _ i + 1), TextObject) MyText.Text = fields(i).ToString() End If Next sql = "SELECT " & firstPart & " " & lastPart Return sql End Function End Class
NOTE : You have to provide the necessary databse information to Connection String.
In this section you can see , creating a Crystal Reports from XML file instead of database . This is very similer to creating Crystal Reports from database , the only difference is to sslect the data source as your XML file. Here we are creating an XML file name is Product is XML file the same structure of the Product table in the sample Database Structure. Download Product.XML
The basics of Crystal Reports creation provided in previous tutorials , if you dont have much knowledge in Crystal Reports , take a look at the tutorial step by step Crystal Report before start this section. The change happen only from previous report , when you select Data for Crsyatl Report , you have to select Create New Connection Database Files and select the XML file you want to generate Crystal Reports (In this case you select the Product.xml ).
Select all the fields from Product and click finish button
Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here.
All Crystal Reports programming samples in this tutorials is based on the following database (crystaldb) . Please take a look at the database structure before you start this tutorial - Click here to see Database Structure . Here we are create an order report based on three tables in the database and show a subreoprt for each row of the specified Product Name. Here we are using our earlier program Crystal Report from multiple tables to show the main Crystal Reports Data , so please refer Crystal Report from multiple tables before start this section . Create a Crystal Reports using three tables and select customername , date , product and qty . It will explain in detail the previous section Crystal Report from multiple tables .
Next step is to create a subreport inside the main report. Here we are showing the Product details in each row of the specified product in the main row. After create the main report , right click on Crystal Reports designer window and select Insert-Subreport.
Then you will get the subreport object , drag the object in the designer window at the down part of the details tab , just below the fields in the details tab. When you release the mouse you will get a dialogue box asking report name . Enter the report name you want and click the Report Wizard button. The wizard shows the table selection screen and select the table . Here in this case we are selecting the Product Table from the list and click next . Next screen is showing the table , from there select the fields you want to show the data and click finish. The you will get the subreport main screen again and select Link tab . The link tab is making relation with your main Report and subreport . Here we are linking the productname from main report to the subreport. For that select Product.Product_name from Available fields.
Accept the other settings as it is in the screen and click ok. Now you can see the subreport object in the screen , if you want to modify subreport design , double click on subreport object and you can design subreport.
Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim crp As New CrystalReport1 CrystalReportViewer1.ReportSource = crp CrystalReportViewer1.Refresh() End Sub End Class
In the previous section Subreport in Crystal Report is described how to insert a subreport in Crystal Reports . In that case the subreport is embedded within the main Crystal Reports. Here we are creating a subreport , and the subreport has only a link in the main Report , on-demand subreports . That is when the user click the link , then only the subreport display.
Here we are using our previous example Subreport in Crystal Report and make a link in the min Crystal Reports for on-demand subreport. Select the subreport object in the Crystal Reports and right click , then select Format Object .
Then you will get Format Editor . Select Subreport tab from Format Editor , you can find there a check box On-demand Subreport . You have to select that check box , then the subreport become as a link in your main Crystal Reports. If you want to change the title , you can change it in subreport name textbox. Finally click OK button.
Now the designing part is over and you are ready to generate subreport on-demand. Next step is to select the default form(Form1.vb) and add a Button and Crystal Report Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim crp As New CrystalReport1 CrystalReportViewer1.ReportSource = crp CrystalReportViewer1.Refresh() End Sub End Class
Steps to create Setup file. 1) Make sure the above mentioned files are in the \Program Files\Common Files\Merge Modules folder , If the files are not there you can download the file and copy it to the folder \Program Files\Common Files\Merge Modules . Download: https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/11688 2) Open your Visual Studio 3) Select "New Project" from File menu.
4) Select "Setup and Deployment" from "Other Project Types" 5) In the "Solution Explorer", select your setup project, right-click, and select Add and Merge Module from the menu.
6) Select CrystalReportsRedist2005_x86.msm to your setup project. The file available at \Program Files\Common Files\Merge Modules
Then you can see Microsoft_VC80_ATL_x86.msm and policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically added in the Detected Depencies section. 7) Build your project. Now you will get the setup file for distribution. Either you can add this setup file to you application installer or distribute it as a separate setup file.
operating systems. In the following sections describes , the basics of Microsoft .Net Frame work Technology and its related programming models.
The Common Language Runtime (CLR) uses metadata to locate and load classes, generate native code, provide security, and execute Managed Code. Both Microsoft Intermediate Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file. Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by Microsoft .Net Framework. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. The native code is Operating System independent and this code is known as Managed Code , that is, the language's functionality is managed by the .NET Framework . The Common Language Runtime (CLR) provides various Just In Time (JIT) compilers, and each works on a different architecture depends on Operating Systems, that means the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems. In the following section you can see how Common Language Runtime (CLR) functions .
The Common Language Runtime (CLR) is the runtime environment of the .Net Framework , that executes and manages all running code like a Virtual Machine. The .Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes. The .Net Framework Class Libraries (FCL) are arranged into a logical grouping according to their functionality and usability is called Namespaces. In the following sections describes how to .Net Framework manages the code in compile time and run time .
The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS). The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. The Managed Code compiled only when it needed, that is it converts the appropriate instructions when each function is called . The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time. During the execution of the program ,the Common Language Runtime (CLR) manages memory, Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS), code safety verifications, and other system services. The CLR ( Common Language Runtime ) defines the Common Type System (CTS), which is a standard type system used by all .Net languages . That means all .NET programming languages uses the same representation for common Data Types , so Common Language Runtime (CLR) is a language-independent runtime environment . The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System. In the coming section you can see what are the main functions of Common Language Runtime (CLR).
The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture . The .Net Framework Class Library (FCL) includes a huge collection of reusable classes , interfaces, and value types that expedite and optimize the development process and provide access to system functionality. The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.
any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.
Managed Code
Managed Code in Microsoft .Net Framework, is the code that has executed by the Common Language Runtime (CLR) environment. On the other hand Unmanaged Code is directly executed by the computer's CPU. Data types, error-handling mechanisms, creation and destruction rules, and design guidelines vary between managed and unmanaged object models. The benefits of Managed Code include programmers convenience and enhanced security . Managed code is designed to be more reliable and robust than unmanaged code , examples are Garbage Collection , Type Safety etc. The Managed Code running in a Common Language Runtime (CLR) cannot be accessed outside the runtime environment as well as cannot call directly from outside the runtime environment. This makes the programs more isolated and at the same time computers are more secure . Unmanaged Code can bypass the .NET Framework and make direct calls to the Operating System. Calling unmanaged code presents a major security risk.
.Net Assembly
Microsoft .Net Assembly is a logical unit of code, it contains code that the Common Language Runtime (CLR) executes. Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. During the compile time Metadata is created, with Microsoft Intermediate Language (MSIL), and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. Manifest contains information about itself. This information is called Assembly Manifest, it contains information about the members, types, references and all the other data that the runtime needs for execution. Every Assembly you create contains one or more program files and a Manifest. There are two types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only one entry point (that is, DllMain, WinMain, or Main). We can create two types of Assembly, private Assembly and shared Assembly . A private Assembly is used only by a single application, and usually it is stored in that application's install directory. A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).
The GAC is automatically installed with the .NET runtime. The global assembly cache is located in 'Windows/WinNT' directory and inherits the directory's access control list that administrators have used to protect the folder. The approach of having a specially controlled central repository addresses the shared library concept and helps to avoid pitfalls of other solutions that lead to drawbacks like DLL hell. The Global Assembly Cache Tool (Gacutil.exe), that allows you to view and manipulate the contents of the Global Assembly Cache.
A private assembly is an assembly that is available to particular application where they are kept, and a Shared Assembly is a public assembly that is shared by multiple applications. That means, a Private Assembly cannot be references outside the scope of the folder where they are kept and a Shared Assembly is one that can be referenced by more than one application. In order to share an assembly, the assembly must be explicitly built for this purpose by giving it a cryptographically strong name . By contrast, a private assembly name need only be unique within the application that uses it. The classes that ship with the .NET Framework are all built as shared assemblies.
.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification. The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET
Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.
Application Domain
An application domain is a virtual process and is used to isolate applications from one another. Each application domain has their own virtual address space which scopes the resources for the application domain using that address space. Each application running within its main process boundaries and its application domain boundaries. All objects created within the same application scope are created within the same application domain. Multiple application domains can exist in a single operating system process. An application running inside one application domain cannot directly access the code running inside another application domain. System.AppDomain is the main class you can use to deal with application domains.
Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the
application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap. The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.
Threads
Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance. Multithreading allows multiple process to execute concurrently within a single program .That is more than one task in a program can execute at the same time and each thread run independently of its own. If multiple threads can exist within a process, typically share the state information of a process, and share memory and other resources directly. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled. In multiple threaded programming we can use system's idle time, so it leads improved application performance . Also we can set priority in each Threads . Threads with higher priority are executed in preference to threads with lower priority. It is recommended that you use as few threads as possible, thereby minimizing the use of Operating System resources . Check the following links to see how Multi Threaded applications works in VB.NET . 1. Multithreaded Socket Programming 2. Multi Threaded Chat Server Program
Multithreaded Socket Programming means that a Multithreaded Server can communicate with more than one clients at the same time . In the previous section Socket Programming , the Server Socket Program can communicate with only one client at a time . That means it s not possible to connect another Client Socket Program at the same time to communicate with Server . From the following figure you can understand how to a Server can communicate with more than one client at the same time .You can see the basics of Socket Programming in the previous section , take a look at Socket Programming before you start this section.
The basic idea behind Multithreaded Socket Programming is, whenever Server gets a connection request from Client , the Server create a separate ( independent ) Thread for the each Client request. That means for each Client, there is a separate Client Thread in Server . So the Client can communicate independently with their own Client Thread in Server.
In the following sections you can see in detail of How a Multithreaded Socket Programming can communicate with more than one client at the same time. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program How to run this program ? Create Multithreaded Server Socket Program and Multithreaded Client Socket Program and run the Server program first . Then you will get message of "Server started" . Next you start the Client program , then you can see the message from Server . You can start
more than one client same time and communicate with Server . For each client Server responds with the Clients Connection ID Number.
Imports System.Net.Mail Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim SmtpServer As New SmtpClient() Dim mail As New MailMessage() SmtpServer.Credentials = New _ Net.NetworkCredential("[email protected]", "password") SmtpServer.Port = 587 SmtpServer.Host = "smtp.gmail.com" mail = New MailMessage() mail.From = New MailAddress("[email protected]") mail.To.Add("TOADDRESS") mail.Subject = "Test Mail" mail.Body = "This is for testing SMTP mail from GMAIL" SmtpServer.Send(mail) MsgBox("mail send") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
You have to provide the informations like your gmail username and password , and the to address also.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim CDOSYS As Object Const cdoSendUsingPickup = 1 Const strPickup = "c:\inetpub\mailroot\pickup" CDOSYS = CreateObject("CDO.Message") CDOSYS.Configuration.Fields.item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") _ = cdoSendUsingPickup CDOSYS.Configuration.Fields.item _ ("http://schemas.microsoft.com/cdo/configuration" & _ /smtpserverpickupdirectory") _ = strPickup CDOSYS.Configuration.Fields.Update() CDOSYS.To = "TO ADDRESS" CDOSYS.From = "FROM ADDRESS" CDOSYS.Subject = "CDO Test" CDOSYS.TextBody = "Send Email from vb.net using CDOSYS"
You have to provide the informations like To Address , From Address and it is very important to enable your SMTP services in IIS .
If you pass localhost in GetHostByName return the IP Address of local machine . Download Source Code Print Source Code
Imports System.Net Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim hostname As IPHostEntry = Dns.GetHostByName(TextBox1.Text) Dim ip As IPAddress() = hostname.AddressList TextBox2.Text = ip(0).ToString() End Sub End Class
Imports System.Net Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim inStream As StreamReader Dim webRequest As WebRequest Dim webresponse As WebResponse webRequest = webRequest.Create(TextBox1.Text) webresponse = webRequest.GetResponse() inStream = New StreamReader(webresponse.GetResponseStream()) TextBox2.Text = inStream.ReadToEnd() End Sub End Class
Once the communication is established , the Server and Client can read or write their own sockets. There are two types of communication protocol use for Socket Programming TCP/IP ( Transmission Control Protocol/Internet protocol ) Communication and UDP/IP ( User Datagram Protocol/Internet protocol ) Communication . In the following section we are going to communicate a Server Socket Program and Client Socket Program through VB.NET using TCP/IP Communication.
In the above picture shows the communication interfaces . Server Socket Program: Here Server Socket Program is done through a Console based VB.NET application . Here the Server listening for the client's request , and when the server get a request from the Client , Server sends the response to Client . Click the following link to see in detail of a Server Socket Program .
Client Socket Program: The Client Socket Program is a windows based application . When the client start its get connect the server and send requests , and also receive the response from Server . Click the following link to see in detail of Client Socket Program. How to run this program ? The Socket Programming has two sections. 1. Server Socket Program 2. Client Socket Program When you finish coding the program , First you have to start Server Socket Program , then you will get the DOS screen with a message Server Started . Next step is to start Client Socket Program . Then you will get message in client screen Client Started , at the same time you check with server screen a message Accept connection from client . Now your Server Socket Program and Client Socket Program get connected . If you want to test the communication , you click the button ( Click here to send data to Server ) in client window , then you can see changes in Server and Client screen messages .
The Socket Programming has two sections. 1. Server Socket Program 2. Client Socket Program The Server Socket Program here is a VB.NET Console based Application . This program act as a Server and listening to clients request . We assign Port 8888 for the Server Socket , it is an instance of the VB.NET Class TcpListener , and call its start() method.
Dim serverSocket As New TcpListener(8888) serverSocket.Start()
Next step we are creating an infinite loop for continuous communication to Client . When Server get the request , it reads the data from NetworkStream and also write the response to NetworkStream . Create a new VB.NET Console Application Project and put the following source code into project.
While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() Dim bytesFrom(10024) As Byte networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) Dim dataFromClient As String = _ System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _ dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("Data from client - " + dataFromClient) Dim serverResponse As String = _ "Server response " + Convert.ToString(requestCount) Dim sendBytes As [Byte]() = _ Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.ToString) End Try End While clientSocket.Close()
serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub End Module
The next part of this section is Client Socket Program . After create the Client Socket Program , you should first start the Server Socket Program and then start the Client Socket Program . If you need more details about this tutorial please refer to Socket Programming Section .
1. Server Socket Program 2. Client Socket Program The Client Socket Program is the continuation of the Server Socket Program . The Client Socket Program is a Windows based application . Client connect to the Port 8888 of the Server Socket Program , and the IP Address (Computer Name) here we give as 127.0.0.1 , because the Server and client running on the same machine . clientSocket.Connect("127.0.0.1", 8888) When client gets connected , it reads data from NetworkStream , and also write to NetworkStream . When you start the client program you will get message client started . When press the button at the bottom its send a message to Server and also receive a message from Server. Download Source Code Print Source Code
Imports System.Net.Sockets Imports System.Text Public Class Form1 Dim clientSocket As New System.Net.Sockets.TcpClient() Dim serverStream As NetworkStream Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim serverStream As NetworkStream = clientSocket.GetStream() Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes("Message from Client$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim inStream(10024) As Byte serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize)) Dim returndata As String = _ System.Text.Encoding.ASCII.GetString(inStream) msg("Data from Server : " + returndata) End Sub Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load msg("Client Started") clientSocket.Connect("127.0.0.1", 8888) Label1.Text = "Client Socket Program - Server Connected ..." End Sub Sub msg(ByVal mesg As String) TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg End Sub End Class
Brfore you run the Client Socket Program you should start Server Socket Program first . For more details of running this program , take a look at the VB.NET Socket Programming .
The basic idea behind Multithreaded Socket Programming is, whenever Server gets a connection request from Client , the Server create a separate ( independent ) Thread for the each Client request. That means for each Client, there is a separate Client Thread in Server . So the Client can communicate independently with their own Client Thread in Server.
In the following sections you can see in detail of How a Multithreaded Socket Programming can communicate with more than one client at the same time. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program How to run this program ? Create Multithreaded Server Socket Program and Multithreaded Client Socket Program and run the Server program first . Then you will get message of "Server started" . Next you start the Client program , then you can see the message from Server . You can start
more than one client same time and communicate with Server . For each client Server responds with the Clients Connection ID Number.
serverSocket.Start() msg("Server Started") counter = 0 While (True) counter += 1 clientSocket = serverSocket.AcceptTcpClient() msg("Client No:" + Convert.ToString(counter) + " started!") Dim client As New handleClinet client.startClient(clientSocket, Convert.ToString(counter)) End While clientSocket.Close() serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Public Sub startClient(ByVal inClientSocket As TcpClient, _ ByVal clineNo As String) Me.clientSocket = inClientSocket Me.clNo = clineNo Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat) ctThread.Start() End Sub Private Sub doChat() Dim requestCount As Integer Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim sendBytes As [Byte]() Dim serverResponse As String Dim rCount As String requestCount = 0
While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _ dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("From client-" + clNo + dataFromClient) rCount = Convert.ToString(requestCount) serverResponse = "Server to clinet(" + clNo + ") " + rCount sendBytes = Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.ToString) End Try End While End Sub End Class End Module
The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program You have to run Server program first and then Client program , then only you can communicate with Server and Client each other .
MultiThreaded Server Socket Program here is a VB.NET Console based application , that can handle multiple clients at the same time. You can see the basics of Socket Programming in the previous section , take a look at Socket Programming before you start this section. The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program Here we create a Server Socket from TcpListener class and listen to PORT 8888 . When the server gets a request from Client , the Server pass the instance of the client request to a separate class handleClient . In handleClient class there is a Thread , handling the communication between the instance of Server side client and Client from outside . For each request , in Server there is a new thread instant is create for communication , so we can connect more than one client at the same time to Server and communicate independently . Create a new VB.NET Console Application project and put the following source code in the project. Download Source Code
Imports System.Net.Sockets Imports System.Text Module Module1 Sub Main() Dim serverSocket As New TcpListener(8888) Dim clientSocket As TcpClient Dim counter As Integer serverSocket.Start() msg("Server Started") counter = 0 While (True) counter += 1 clientSocket = serverSocket.AcceptTcpClient() msg("Client No:" + Convert.ToString(counter) + " started!") Dim client As New handleClinet
client.startClient(clientSocket, Convert.ToString(counter)) End While clientSocket.Close() serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Public Sub startClient(ByVal inClientSocket As TcpClient, _ ByVal clineNo As String) Me.clientSocket = inClientSocket Me.clNo = clineNo Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat) ctThread.Start() End Sub Private Sub doChat() Dim requestCount As Integer Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim sendBytes As [Byte]() Dim serverResponse As String Dim rCount As String requestCount = 0 While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("From client-" + clNo + dataFromClient) rCount = Convert.ToString(requestCount) serverResponse = "Server to clinet(" + clNo + ") " + rCount sendBytes = Encoding.ASCII.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) Catch ex As Exception MsgBox(ex.ToString) End Try End While End Sub End Class End Module
The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program You have to run Server program first and then Client program , then only you can communicate with Server and Client each other .
clientSocket.Connect("127.0.0.1", 8888) When the Client get conncted to the Server , the Server make a separate thread for Client's communication . So we can connect more than one client and communicate at the same time. Create a new VB.NET Windows based application and put the following source code in the Project. Download Source Code Print Source Code
Imports System.Net.Sockets Imports System.Text Public Class Form1 Dim clientSocket As New System.Net.Sockets.TcpClient() Dim serverStream As NetworkStream Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim serverStream As NetworkStream = clientSocket.GetStream() Dim buffSize As Integer Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes("Message from Client$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim inStream(10024) As Byte buffSize = clientSocket.ReceiveBufferSize serverStream.Read(inStream, 0, buffSize) Dim returndata As String = _ System.Text.Encoding.ASCII.GetString(inStream) msg("Data from Server : " + returndata) End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load msg("Client Started") clientSocket.Connect("127.0.0.1", 8888) Label1.Text = "Client Socket Program - Server Connected ..." End Sub Sub msg(ByVal mesg As String)
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg End Sub End Class
The Multithreaded Socket Programming has two sections. 1. Multithreaded Server Socket Program 2. Multithreaded Client Socket Program You have to run Server program first and then Client program , then only you can communicate with Server and Client each other .
Each Clients send messages to Server and the Server broadcast the message to all Clients currently connected to the Chat Server . From the following diagram you can see how a VB.NET TCP Chat Server is handling communication between Client to Client .
The VB.NET Multithreaded Chat Server program has two sections. 1. Chat Server 2. Chat Client Download Chat Server Program . Chat Server Download Chat Client Download
How to run Chat Server program ? After create the Chat Server and Chat Client , run the Server program first and then run the Client program . In the Client program Enter a Chat name and click the " Connect to Server " button . Then you can see the message in the Server program User Joined Chat Room . Similarly you can connect more than one Clients at the same time and start chatting each other. It is better to Compile and Build the program and run from the .exe files .
The VB.NET Multithreaded Chat Server Program has two sections. 1. Chat Server 2. Chat Client
The Chat Server here is a VB.NET Console based application and is listening to the PORT 8888 for the connection request from clients . When the server gets a connection request , it add the name of the Client into a clientsList ( Here it is a Hashtable ) and create a new thread for communication with Server . When the Server get a message from any client , it select all the Clients from clientsList and send the message to all Clients ( ie we can say Broadcast ) in the clientsList . So each Client can see the message each other and they can communicate through Chat Server. The client list we implemented here in a HashTable . The clientsList stores the Client Name ( ie the first message from Client ) and an instance of the Client Socket . When a Chat Client connected to Server , the Server create a new Thread for communication . Here we implement a Class handleClient for handling Client as a separate Thread . The Class handleClient has a function doChat() is handling the communication between the Server side Client Socket and the incoming Client Socket. When Server get a message from any of the currently connected Chat Client , the Server Broadcast the message to all Clients. Here we implement a function broadcast for sending messages to all Clients . Create a new VB.NET Console based application and put the following source code into the Project. Download Source Code
Imports System.Net.Sockets Imports System.Text Module Module1 Dim clientsList As New Hashtable Sub Main() Dim serverSocket As New TcpListener(8888) Dim clientSocket As TcpClient Dim counter As Integer serverSocket.Start() msg("Chat Server Started ....") counter = 0 While (True) counter += 1 clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _ dataFromClient.Substring(0, dataFromClient.IndexOf("$")) clientsList(dataFromClient) = clientSocket broadcast(dataFromClient + " Joined ", dataFromClient, False) msg(dataFromClient + " Joined chat room ") Dim client As New handleClinet client.startClient(clientSocket, dataFromClient, clientsList) End While clientSocket.Close() serverSocket.Stop() msg("exit") Console.ReadLine() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Console.WriteLine(" >> " + mesg) End Sub Private Sub broadcast(ByVal msg As String, _ ByVal uName As String, ByVal flag As Boolean) Dim Item As DictionaryEntry For Each Item In clientsList Dim broadcastSocket As TcpClient broadcastSocket = CType(Item.Value, TcpClient) Dim broadcastStream As NetworkStream = _ broadcastSocket.GetStream() Dim broadcastBytes As [Byte]() If flag = True Then broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else broadcastBytes = Encoding.ASCII.GetBytes(msg) End If broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length) broadcastStream.Flush() Next End Sub Public Class handleClinet Dim clientSocket As TcpClient Dim clNo As String Dim clientsList As Hashtable Public Sub startClient(ByVal inClientSocket As TcpClient, _ ByVal clineNo As String, ByVal cList As Hashtable) Me.clientSocket = inClientSocket Me.clNo = clineNo Me.clientsList = cList Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat) ctThread.Start() End Sub Private Sub doChat() 'Dim infiniteCounter As Integer Dim requestCount As Integer Dim bytesFrom(10024) As Byte Dim dataFromClient As String Dim sendBytes As [Byte]() Dim serverResponse As String Dim rCount As String requestCount = 0 While (True) Try requestCount = requestCount + 1 Dim networkStream As NetworkStream = _ clientSocket.GetStream() networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom) dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$")) msg("From client - " + clNo + " : " + dataFromClient) rCount = Convert.ToString(requestCount) broadcast(dataFromClient, clNo, True) Catch ex As Exception MsgBox(ex.ToString) End Try End While End Sub End Class End Module
Download Chat Server Program . Chat Server Download Chat Client Download Refer to Chat Server Program for how to run this program .
The VB.NET Multithreaded Chat Server Program has two sections. 1. Chat Server 2. Chat Client The Chat Client here is to connect the PORT 8888 of the Chat Server in " 127.0.0.1 " . Here we give " 127.0.0.1 " , because Chat Server and Chat Client are running on the same machine . When we start the Chat Client program , we have to enter a User Name for identifying in Server . The Client program connect to the Chat Server and start a Thread for receive the messages from client, . Here we implement an infinite loop in the function getMessage() and call this function in a Thread . Create a new VB.NET Windows based project and put the source code in it. Download Source Code
Imports System.Net.Sockets Imports System.Text Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes(TextBox2.Text + "$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() End Sub Private Sub msg() If Me.InvokeRequired Then Me.Invoke(New MethodInvoker(AddressOf msg)) Else TextBox1.Text = TextBox1.Text + _ Environment.NewLine + " >> " + readData End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click readData = "Conected to Chat Server ..." msg() clientSocket.Connect("127.0.0.1", 8888) 'Label1.Text = "Client Socket Program - Server Connected ..." serverStream = clientSocket.GetStream() Dim outStream As Byte() = _ System.Text.Encoding.ASCII.GetBytes(TextBox3.Text + "$") serverStream.Write(outStream, 0, outStream.Length) serverStream.Flush() Dim ctThread As Threading.Thread = _ New Threading.Thread(AddressOf getMessage) ctThread.Start() End Sub Private Sub getMessage()
For infiniteCounter = 1 To 2 infiniteCounter = 1 serverStream = clientSocket.GetStream() Dim buffSize As Integer Dim inStream(10024) As Byte buffSize = clientSocket.ReceiveBufferSize serverStream.Read(inStream, 0, buffSize) Dim returndata As String = _ System.Text.Encoding.ASCII.GetString(inStream) readData = "" + returndata msg() Next End Sub End Class
Download Chat Server Program . Chat Server Download Chat Client Download Refer to Chat Server Program for how to run this program .
InternetGetConnectedState function retrieves the connected state of the local system. A return value of TRUE from InternetGetConnectedState indicates that at least one connection to the Internet is available. Download Source Code
Imports System.Runtime.InteropServices Public Class Form1 Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef conn As Long, ByVal val As Long) As Boolean Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Out As Integer If InternetGetConnectedState(Out, 0) = True Then MsgBox("Connected !") Else MsgBox("Not Connected !") End If End Sub End Class
Trying to match these restrictions is a complex task, often resulting in long regular expressions. The .NET Framework provides an extensive set of regular expression tools that enable you to efficiently create, compare, and modify strings as well as rapidly parse large amounts of text and data to search for, remove, and replace text patterns.
Regex.IsMatch("[email protected]", pattern)
Regex.IsMatch Method (String, String) Indicates whether the specified regular expression finds a match in the specified input string. The pattern parameter consists of various regular expression language elements that symbolically describe the string to match pattern . The following vb.net source code shows how to validate an email address with the help of regular expressions. Download Source Code
Imports System.Text.RegularExpressions Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim pattern As String pattern = "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zAZ]{2,9})$" If Regex.IsMatch("[email protected]", pattern) Then MsgBox("Valid Email address ") Else MsgBox("Not a valid Email address ") End If End Sub End Class
Using Directory class , we can create , delete , move etc. operations in VB.NET. Because of the static nature of Directory class , we do not have to instantiate the class. We can call the methods in the class directly from the Directory class. How to create a directory ? In order to create a new directory , we can call CreateDirectory directly from Directory class. Syntax : Directory.CreateDirectory(DirPath) DirPath : The name of the new directory VB.NET : Directory.CreateDirectory("c:\testdir") How to check a directory exist or not ? Before we creating a directory , we usually check that directory exist or not. For that we are using the Exists method in the Directory class. Syntax : Directory.Exists(DirPath) as Boolean DirPath : The name of the directory Boolean : Returns true or false , if directory exist it Returns true , else it Returns false VB.NET : Directory.Exists("c:\testdir") How to move a Directory ? If we want to move a directory and its contents from one location to another , we can use the Move method in the Directory class. Syntax : Move(sourceDirName,destDirName) sourceDirName : The source directory we want to move.
destDirName : The destinations directory name. VB.NET : Directory.Move("c:\testdir1\testdir2", "c:\testdir") How to delete a Directory ? When we want to delete a directory we can use the Delete method in the Directory class Syntax : Delete(DirPath) DirPath : The Directory we want to delete. VB.NET : Directory.Delete("c:\testdir1") The following VB.NET source code shows these operations : Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click If Directory.Exists("c:\testDir1") Then 'shows message if testdir1 exist MsgBox("Directory 'testDir' Exist ") Else 'create the directory testDir1 Directory.CreateDirectory("c:\testDir1") MsgBox("testDir1 created ! ") 'create the directory testDir2 Directory.CreateDirectory("c:\testDir1\testDir2") MsgBox("testDir2 created ! ") 'move the directory testDir2 as testDir in c: "c:\testDir") MsgBox("testDir2 moved ") 'delete the directory testDir1 Directory.Delete("c:\testDir1") MsgBox("testDir1 deleted ")
Directory.Move("c:\testDir1\testDir2",
When you executing this program you can see , first it create directory testDir1 and then testDir2 is creating inside testDir1 , Next the program move the testDir2 to testDir . Finally it delete the directory testDir1. After the execution you can see testDir in c:\
VB.NET : File.Exists("c:\testFile.txt") The following VB.NET source code shows these operations :
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If File.Exists("c:\testFile.txt") Then 'shows message if testFile exist MsgBox("File 'testFile' Exist ") Else 'create the file testFile.txt File.Create("c:\testFile.txt") MsgBox("File 'testFile' created ") End If End Sub End Class
When you execute this source code , it first check the File exist or not , If exist it shows message file exist , else it create a new File Object . How to Copy a File ? If we want the Copy of the File Object we can use the Copy method in File class. Syntax : Copy(sourceFileName, destFileName) sourceFileName : The source file we want to move. destFileName : The destinations file name. VB.NET : File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt") How to delete a File Object ?
When we want to delete a File Object we can use the Delete methods in the File class Syntax : Delete(FilePath) DirPath : The File Object you want to delete. VB.NET : File.Delete("c:\testDir\testFile.txt") The following VB.NET source code shows these operations : Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If Not File.Exists("c:\testFile.txt") Then MsgBox("FIle not exist ") Else File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt") MsgBox("File Copied ") File.Delete("c:\testFile.txt") MsgBox("file deleted ") End If End Sub End Class
When you execute this program first it check whether the file exist or not , if it is not exist it shows message file does not exist, if it exist it copied the file to testDir director and it delete the file from the c:\.
Some of FileModes as Follows : FileMode.Append : Open and append to a file , if the file does not exist , it create a new file FileMode.Create : Create a new file , if the file exist it will append to it FileMode.CreateNew : Create a new File , if the file exist , it throws exception FileMode.Open : Open an existing file How to create a file using VB.NET FileStream ? The following example shows , how to write in a file using FileStream. Download Source Code Print Source Code
Imports System.IO Imports System.Text Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim wFile As System.IO.FileStream Dim byteData() As Byte byteData = Encoding.ASCII.GetBytes("FileStream Test1") wFile = New FileStream("streamtest.txt", FileMode.Append) wFile.Write(byteData, 0, byteData.Length) wFile.Close() Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When we execute the program , it create a new File and write the content to it .
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim line As String Dim readFile As System.IO.TextReader = New _ StreamReader("C:\TextReader.txt") While True line = readFile.ReadLine() If line Is Nothing Then Exit While Else MsgBox(line) End If End While readFile.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When you execute this program the TextReader read the file line by line.
Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. The following program using TextReader , Read the entire content of the file into a String Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim line As String Dim readFile As System.IO.TextReader = New _ StreamReader("C:\Test1.txt") line = readFile.ReadToEnd() MsgBox(line) readFile.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When you execute this program , TextReader read the entire file in one stretch.
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim writeFile As System.IO.TextWriter = New _ StreamWriter("c:\textwriter.txt") writeFile.WriteLine("vb.net-informations.com") writeFile.Flush() writeFile.Close() writeFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When you execute this source code , you will get a file TextWriter.txt and inside it written vb.net-informations.com
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim readStream As FileStream Dim msg As String Try readStream = New FileStream("c:\testBinary.dat", FileMode.Open) Dim readBinary As New BinaryReader(readStream) msg = readBinary.ReadString() MsgBox(msg) readStream.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization. Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay.Write("This is a test for BinaryWriter !") writeBinay.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization. Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay.Write("This is a test for BinaryWriter !") writeBinay.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
IOException is the base class for exceptions thrown while accessing information using streams, files and directories. FileNotFoundException Class is thrown the exception when an attempt to access a file that does not exist on disk fails.
Try
The following vb.net program shows how to use File Class for copying and deleting a text file and also its shows how to handle System.IO.FileNotFoundException Class. Download Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try File.Copy("c:\\temp.txt", "c:\\copytemp.txt", True) File.Delete("c:\\copytemp.txt") Catch ex As System.IO.FileNotFoundException MsgBox(ex.ToString()) End Try End Sub End Class
VB.NET ADO.NET
The two key components of ADO.NET are Data Providers and DataSet . The .Net Framework includes mainly three Data Providers for ADO.NET. The Microsoft SQL Server , OLEDB and ODBC are the main Data Providers in the .Net Framework. In the following pages you can see each component of ADO.NET in details with source code.
ADO.NET Architecture
ADO.NET is a data access technology from Microsoft .Net Framework , which provides communication between relational and nonrelational systems through a common set of components . ADO.NET consist of a set of Objects that expose data access services to the .NET environment. ADO.NET is built for disconnected architecture , so it enables truly disconnected Data Access and Data Manipulation through its Dataset Object, which is completely independent from the Data Source.
The two key components of ADO.NET are Data Providers and DataSet . The .Net Framework includes mainly three Data Providers for ADO.NET. They are the Microsoft SQL Server Data Provider, OLEDB Data Provider and ODBC Data Provider. SQL Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses OdbcConnection Object respectively.
The four Objects from the .Net Framework provide the functionality of Data Providers in the ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object. The Connection Object provides physical connection to the Data Source. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data Source. The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. Finally the DataAdapter Object , which populate a Dataset Object with results from a Data Source .
DataSet provides a disconnected representation of result sets from the Data Source, and it is completely independent from the Data Source. DataSet provides much greater flexibility when dealing with related Result Sets. DataSet consists of a collection of DataTable
objects that you can relate to each other with DataRelation objects. The DataTable contains a collection of DataRow and DataCoulumn Object which contains Data. The DataAdapter Object provides a bridge between the DataSet and the Data Source.
In the following section you can see each of the ADO.NET components in details with vb.net source code.
A major difference in creating connections with ADO and ADO.NET is that ADO fits all connections to all types of data sources into a single Connection object. ADO.NET can have separate Objects that represent connections to different data sources. In ADO.NET you can create multiple data provider namespaces to connect specifically with a particular data source, making access faster and more efficient and allowing each namespace to exploit the features of its targeted data provider.
Dim connection As SqlConnection connection = New SqlConnection("connetionString") Dim connection As OleDbConnection connection = New OleDbConnection("connetionString")
ADO allows you to create client side cursors only whereas ADO.NET gives you the choice of either using client side or server side cursors. ADO.NET introduces a new way of getting a single value from a query's results when you expect only one row and one column to return. The ADO.NET command object has an ExecuteScalar method which returns the first row and column's value from its associated query. ADO.Net dataset represents in memory representation of a database. ADO recordsets is merely a set of rows retrieved from a data source. ADO recordsets can hold data from one data source at a time. ADO.Net datasets can hold data from various sources and integrate the data and write it back to one or several data sources. The ADO.NET Framework supports two models of Data Access Architecture, Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. In the case of Data Communication , ADO objects communicate in binary mode while ADO.NET uses XML for passing the data. You can find more information on ADO to ADO.NET from the following link : http://msdn.microsoft.com/en-us/magazine/cc163954.aspx
In Connection Oriented Data Access, when you read data from a database by using a DataReader object, an open connection must be maintained between your application and the Data Source. Unlike the DataReader, the DataSet is not connected directly to a Data Source through a Connection object when you populate it. It is the DataAdapter that manages connections between Data Source and Dataset by fill the data from Data Source to the Dataset and giving a disconnected behavior to the Dataset. The DataAdapter acts as a bridge between the Connected and Disconnected Objects.
Dim adapter As New SqlDataAdapter("sql", "connection") Dim ds As New DataSet adapter.Fill(ds, "Src Table")
By keeping connections open for only a minimum period of time, ADO .NET conserves system resources and provides maximum security for databases and also has less impact on system performance.
ADO.NET ConnectionString
Connection String is a normal String representation which contains Database connection information to establish the connection between Datbase and the Application. The Connection String includes parameters such as the name of the driver, Server name and Database name , as well as security information such as user name and password. Data providers use a connection string containing a collection of parameters to establish the connection with the database. The .NET Framework provides mainly three data providers: Microsoft SQL Server, OLEDB and ODBC. Here you can see how to make connection string to these ADO.NET Data Providers. Microsoft SQL Server Connection String connetionString ="Data Source = ServerName; Initial Catalog = Databasename; User ID = UserName; Password=Password" OLEDB Data Provider Connection String connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = yourdatabasename.mdb;" ODBC Connection String connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ = yourdatabasename.mdb;" Note : You have to provide the necessary informations to the Connection String attributes. In the following section you can see how to these ADO.NET Data Providers establish connection to the Databse in detail. SQL Server Connection OLEDB Connection ODBC Connection
The .Net Framework includes mainly three Data Providers for ADO.NET. They are the Microsoft SQL Server Data Provider , OLEDB Data Provider and ODBC Data provider. You can see from the following links how these Data Providers making connection to the specified data Sources. SQL Server Connection OLEDB Connection ODBC Connection
The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object. The following link shows in details about these Objects. Connection Command DataReader DataAdapter
Here is the solution for how to handle DBNull. The DBNull class represents a nonexistent value. The function IsDBNull returns True if the data type of expression evaluates to the DBNull type otherwise, IsDBNull returns False.
If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.Tables(0).Rows(i).Item(0))) End If
In the above code we are using the function IsDBNull to check wether the Dataset value is a DBNULL or not. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "your sql select statements here"
connection = New SqlConnection(connetionString) connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) connection.Close() Try If IsDBNull(ds.Tables(0).Rows(i).Item(0)) Then MsgBox("DBNULL exist in the field ") Else MsgBox(CInt(ds.Tables(0).Rows(i).Item(0))) End If Catch ex As Exception MsgBox(ex.ToString()) End Try End Sub End Class
Incorrect syntax near '..'. Unclosed quotation mark after the character string ')'. We are getting the above error message because there is a problem while inserting single quoted character using in sql statements. For ex: We want to insert a string like "Microsoft's" , the system shows the above error messages, because we are trying to insert a single quoted character using in sql statement. We can solve this problem by replace any single quote with two quotes like "Microsoft''s" .
For avoiding each time adding another single quote to the string , here we implement a function to replace the string with two single quotes.
Public Function convertQuotes(ByVal str As String) As String convertQuotes = str.Replace("'", "''") End Function
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String Dim field1 As String = "Microsoft's" Dim field2 As String = "VB.NET" connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "insert into tablename (field1,field2) values('" & convertQuotes(field1) & "','" & convertQuotes(field2) & "')" Try connection.Open() adapter.InsertCommand = New SqlCommand(sql, connection) adapter.InsertCommand.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub
'here is the function to handle single quoted characters Public Function convertQuotes(ByVal str As String) As String convertQuotes = str.Replace("'", "''") End Function End Class
The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object. The Connection Object provides physical connection to the Data Source. The Command Object uses to perform SQL statement or stored procedure to be executed at the Data Source. The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. Finally the DataAdapter Object , which populate a Dataset Object with results from a Data Source . The following link shows in details about these Objects. Connection Command DataReader DataAdapter
Royalty Free and Excel Compatible - SpreadsheetGear for .NET Featuring the fastest and most complete Excel compatible calculation engine - Download a free 30-day evaluation today! C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.
In ADO.NET the type of the Connection is depend on what Database system you are working with. The following are the commonly using the connections in the ADO.NET SqlConnection OleDbConnection OdbcConnection
C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details. Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
The SqlConnection Object is Handling the part of physical communication between the application and the SQL Server Database. An instance of the SqlConnection class in .NET Framework is supported the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the database resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the SQL Server Database.
Download Source Code Print Source Code
Take our 3-Minute Hosting Decisions Survey Working Effectively with Legacy Code Participants will be eligible to win a $100 Amazon gift certificate. Take Learn how to find and create seams in your application, no matter the short survey here. "Legacy" it may be, and over time improve application's design. Read more...
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
You have to provide the necessary informations to the Connection String. connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password"
From the above statement replace ServerName, DatabaseName, UserName, Password to the actual names.
In ADO.NET the type of the Connection is depend on what Database system you are working with. The following are the commonly using the connections in the ADO.NET SqlConnection OleDbConnection OdbcConnection
Working Effectively with Legacy Code Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...
Working Effectively with Legacy Code Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString)
Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
You have to provide the necessary informations to the Connection String. connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" From the above statement replace ServerName, DatabaseName, UserName, Password to the actual names.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;" cnn = New OleDbConnection(connetionString)
Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
You have to provide the necessary informations to the Connection String. connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = yourdatabasename.mdb;" From the above statement replace yourdatabasename.mdb to the actual names.
Imports System.Data.Odbc Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String Dim cnn As OdbcConnection connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;" cnn = New OdbcConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
You have to provide the necessary informations to the Connection String. connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ = yourdatabasename.mdb;" From the above statement replace yourdatabasename.mdb to the actual names.
In ADO.NET the type of the Connection is depend on what Database system you are working with. The following are the commonly using the connections in the ADO.NET SqlConnection OleDbConnection OdbcConnection
ADO.NET Command
The Command Object in ADO.NET executes SQL statements and Stored Procedures against the data source specified in the Connection Object. The Command Object required an instance of a Connection Object for executing the SQL statements. That is, for retrieving data or execute an SQL statement against a Data Source , you have to create a Connection Object and open a connection to the Data Source, and assign the open connection to the connection property of the Command Object. When the Command Object return result set , a Data Reader is used to retrieve the result set.
The Command Object has a property called CommandText, which contains a String value that represents the command that will be executed in the Data Source. When the CommandType property is set to StoredProcedure, the CommandText property should be set to the name of the stored procedure. Click the following links to see some important built in methods uses in the Command Object to execute the SQL statements. ExecuteNonQuery ExecuteReader ExecuteScalar
The following example shows how to use the method ExecuteNonQuery() through SqlCommand Object. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(Sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close() MsgBox(" ExecuteNonQuery in SqlCommand executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here" You have to replace the string with your realtime variables.
ExecuteNonQuery() is one of the most frequently used method in OleDbCommand Object and is used for executing statements that do not return result set. ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update and Delete perform by ExecuteNonQuery(). The following example shows how to use the method ExecuteNonQuery() through OleDbCommand Object. Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close() MsgBox(" ExecuteNonQuery in OleDbConnection executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose() cnn.Close() MsgBox(" No. of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ")
connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose()
cnn.Close() MsgBox(" No of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String Dim reader As SqlDataReader connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " End While reader.Close() cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here , like Select * from product" You have to replace the string with your realtime variables.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String Dim reader As OleDbDataReader connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " End While reader.Close() cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.
DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The DataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object.
DataReader = Command.ExecuteReader() DataReader Object provides a connection oriented data access to the data Sources. A Connection Object can contain only one DataReader at a time and the connection in the DataReader remains open and cannot be used for any other purpose while data is being accessed. When started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . DataReader.Raed() There are two types of DataReader in ADO.NET. They are SqlDataReader and the OleDbDataReader. The System.Data.SqlClient and System.Data.OleDb are containing these DataReaders respectively. From the following link you can see in details about these classes. SqlDataReader OleDbDataReader
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " End While
sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" You have to replace the string with your realtime variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbCmd = New OleDbCommand(sql, oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() While oledbReader.Read MsgBox(oledbReader.Item(0) & " - " & oledbReader.Item(1) & " End While oledbReader.Close() oledbCmd.Dispose() oledbCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.
In some situations we need to pass multiple SQL statements to the Command Object. In this situations the SqlDataReader returns multiple ResultSets also. For retrieveing multiple ResultSets from SqlDataReader we use the NextResult() method of the SqlDataReader. SqlDataReader.NextResult() In the following source code demonstrating how to get multiple result sets from SqlDataReader() . Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox("From first SQL - " & sqlReader.Item(0) & " End While sqlReader.NextResult() While sqlReader.Read() MsgBox("From second SQL End While " & sqlReader.Item(0) & " " & sqlReader.Item(1))
sqlReader.NextResult() While sqlReader.Read() MsgBox("From third SQL End While " & sqlReader.Item(0) & " " & sqlReader.Item(1))
sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails" You have to replace the string with your realtime variables.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() Dim schemaTable As DataTable = sqlReader.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.Rows For Each column In schemaTable.Columns MsgBox(String.Format("{0} = {1}", column.ColumnName, row(column))) Next Next sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" You have to replace the string with your realtime variables.
The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. When the ExecuteReader method in oledbCmd Object execute , it instantiate a OleDb.OleDbDataReader Object. Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() While a OleDbDataReader is open, you can retrieve schema information about the current result set using the GetSchemaTable method. GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result set. Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbCmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbCmd = New OleDbCommand(sql, oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() Dim schemaTable As DataTable = oledbReader.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.Rows For Each column In schemaTable.Columns MsgBox(String.Format("{0} = {1}", column.ColumnName, row(column))) Next Next oledbReader.Close() oledbCmd.Dispose() oledbCnn.Close()
Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.
What is DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication between the Dataset and the Datasource. We can use the DataAdapter in combination with the DataSet Object. That is these two objects combine to enable both data access and data manipulation capabilities.
The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source. The Insert , Update and Delete SQL operations , we are using the continuation of the Select command perform by the DataAdapter. That is the DataAdapter uses the Select statements to fill a DataSet and use the other three SQL commands (Insert, Update, delete) to transmit changes back to the Database. From the following links describe how to use SqlDataAdapter and OleDbDataAdapter in detail. SqlDataAdapter
OleDbDataAdapter
What is SqlDataAdapter
SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset Object. Dim adapter As New SqlDataAdapter The SqlDataAdapter Object and DataSet objects are combine to perform both data access and data manipulation operations in the SQL Server Database. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the SqlDataAdapter. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserNamePassword=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) adapter.SelectCommand = sqlCmd adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next adapter.Dispose() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
--
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" You have to replace the string with your realtime variables.
What is OleDbDataAdapter
OleDbDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.OleDb namespace. OleDbDataAdapter provides the communication between the Dataset and the OleDb Data Sources. We can use OleDbDataAdapter Object in combination with Dataset Object. The OleDbDataAdapter Object and DataSet objects are combine to perform both Data Access and Data Manipulation operations in the OleDb Data Sources. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the OleDbDataAdapter. Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet
Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbAdapter = New OleDbDataAdapter(sql, oledbCnn) oledbAdapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " & Next oledbAdapter.Dispose() oledbCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
ds.Tables(0).Rows(i).Item(1))
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.
reader.Close()
ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
Dim retValue As Integer Command = New SqlCommand(Sql, Connection) retValue = Command.ExecuteNonQuery()
The above code create a procedure named as 'SPPUBLISHER' and it execute SQL statement that select all publisher name from publishers table from the PUB database. Using stored procedures, database operations can be encapsulated in a single command, optimized for best performance, and enhanced with additional security. To call a stored procedure from VB.NET application, set the CommandType of the Command object to StoredProcedure.
command.CommandType = CommandType.StoredProcedure
From the following source code you can see how to call a stored procedure from VB.NET application. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1.Click Dim Dim Dim Dim Dim Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connetionString As String connection As SqlConnection adapter As SqlDataAdapter command As New SqlCommand ds As New DataSet
Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPPUBLISHER" adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class
The ADO.NET classes are divided into two components, Data Providers and DataSet. A .NET data provider is used to connect to a database, execute commands, and retrieve results. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions. A Stored Procedure contain programming statements that perform operations in the database, including calling other procedures. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY @COUNTRY VARCHAR(20) AS SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY GO
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String command.Parameters.Add(param)
The above code passing country parameter to the stored procedure from vb.net. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection
Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPCOUNTRY" param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String command.Parameters.Add(param) adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class
DataAdapter is a part of the ADO.NET Data Provider. Dataset represents a collection of data retrieved from the Data Source and saving data to the Data Source. We can use Dataset in combination with DataAdapter class. These two objects combine to enable both data access and data manipulation capabilities. Functionally DataAdapter is the complex Object when compare to other Objects in the Data Provider .
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter = New SqlDataAdapter("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1))
Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter("Your SQL Statement Here") oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter.SelectCommand = New SqlCommand("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox(ex.ToString)
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter.SelectCommand = New OleDbCommand("Your SQL Statement Here", connection) oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub
End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "insert into product (Product_id,Product_name,Product_price) values(7,'Product7',700)" Try connection.Open() adapter.InsertCommand = New SqlCommand(sql, connection) adapter.InsertCommand.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object . The InsertCommand in OleDbDataAdapter Object manages to insert the data in the specified Data Source . In the following Source Code shows how to insert data in the Data Source using OleDbDataAdapter and OleDbCommand object. Open a connection to the Data Source with the help of OleDbConnection object and create an OleDbCommand object with insert SQL statement, and assign the OleDbCommand to the SqlDataAdapter's InsertCommand.
Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "insert into user values('user1','password1')" Try connection.Open() oledbAdapter.InsertCommand = New OleDbCommand(sql, connection) oledbAdapter.InsertCommand.ExecuteNonQuery() MsgBox("Row(s) Inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "update product set product_price = 1001 where Product_name ='Product7'" Try connection.Open() adapter.UpdateCommand = connection.CreateCommand adapter.UpdateCommand.CommandText = sql adapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "update Users set Password = 'new password' where UserID = 'user1'" Try connection.Open() oledbAdapter.UpdateCommand = connection.CreateCommand oledbAdapter.UpdateCommand.CommandText = sql oledbAdapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row(s) Updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString)
sql = "delete product where Product_name ='Product7'" Try connection.Open() adapter.DeleteCommand = connection.CreateCommand adapter.DeleteCommand.CommandText = sql adapter.DeleteCommand.ExecuteNonQuery() MsgBox("Row(s) deleted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "delete from Users where UserID = 'user1'" Try connection.Open() oledbAdapter.DeleteCommand = connection.CreateCommand oledbAdapter.DeleteCommand.CommandText = sql oledbAdapter.DeleteCommand.ExecuteNonQuery() MsgBox("Row(s) Deleted !! ")
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim cmdBuilder As SqlCommandBuilder Dim ds As New DataSet Dim sql As String Dim i As Int32 connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(sql, connection) cmdBuilder = New SqlCommandBuilder(adapter)
adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 ds.Tables(0).Rows(i).Item(2) = ds.Tables(0).Rows(i).Item(2) + 100 Next adapter.Update(ds.Tables(0)) connection.Close() MsgBox("Data updated ! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim oledbCmdBuilder As OleDbCommandBuilder Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
connection = New OleDbConnection(connetionString) sql = "select * from tblUsers" Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) oledbAdapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 ds.Tables(0).Rows(i).Item(2) = "[email protected]" Next oledbAdapter.Update(ds.Tables(0)) connection.Close() MsgBox("Email address updates !") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(Sql, connection) adapter.Fill(ds) connection.Close() DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try cmdBuilder = New SqlCommandBuilder(adapter) changes = ds.GetChanges() If changes IsNot Nothing Then adapter.Update(changes) End If MsgBox("Changes Done") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
OleDbDataAdapter provides the communication between the Dataset and the OLEDB Data Source with the help of OleDbConnection Object . The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects. The TableMapping Collection help the OleDbDataAdapter to do this task. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object. The following source code demonstrate how to update a Dataset through OleDbDataAdapter using a DataGridView. For running this source code , open a new VB.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code.
Download Source Code
Imports System.Data.OleDb Public Class Form1 Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim oledbCmdBuilder As OleDbCommandBuilder Dim ds As New DataSet Dim changes As DataSet Dim i As Integer Dim sql As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Sql = "select * from tblUsers" Try connection.Open() oledbAdapter = New OleDbDataAdapter(Sql, connection) oledbAdapter.Fill(ds) DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button2.Click Try oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) changes = ds.GetChanges() If changes IsNot Nothing Then oledbAdapter.Update(ds.Tables(0)) End If ds.AcceptChanges() MsgBox("Save changes") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
VB.NET DataAdapter.Fill
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet.
DataAdapter.Fill(DataSet) DataAdapter.Fill(DataTable)
The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. If the data adapter encounters duplicate columns while populating a DataTable, it generates names for the subsequent columns, using the pattern "columnname1", "columnname2", "columnname3", and so on. From the following program you can understand how to use DataAdapter.Fill method in VB.NET applications. Download Source Code
Imports System.IO Imports System.Data.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Dim sqlAdp As SqlDataAdapter Dim ds As New DataSet Dim dt As New DataSet
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=userid; Password=password" cnn = New SqlConnection(connectionString) cnn.Open() sqlAdp = New SqlDataAdapter("select * from users", cnn) cnn.Close() 'connection close here , that is disconnected from data source sqlAdp.Fill(ds) sqlAdp.Fill(dt) 'fetching data from dataset in disconnected mode For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next 'fetching data from datatable in disconnected mode For i = 0 To dt.Tables(0).Rows.Count - 1 MsgBox(dt.Tables(0).Rows(i).Item(0)) Next End Sub End Class
In some situations we need to retrieve data only specific range of rows. In this situations we can fill the Dataset from DataAdapter only that specific range of rows. The following piece of code shows how to fill specific range of rows from DataAdapter to Dataset.
DataAdapter.Fill(Dataset, 5, 3, "tablename")
The above code will fill the Dataset starting from 5th row and no of rows 3. 5 is the starting row no 3 is no of rows we want to fill. Download Source Code
imports System.IO Imports System.Data.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Dim sqlAdp As SqlDataAdapter Dim ds As New DataSet Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=userid; Password=password" cnn = New SqlConnection(connectionString) cnn.Open() sqlAdp = New SqlDataAdapter("select * from users", cnn) cnn.Close() sqlAdp.Fill(ds, 5, 3, "users") '5 is starting row no. '3 is no of rows to retrieve For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next End Sub End Class
dataView = dataSet.Tables(0).DefaultView The following source code shows how to create a DataView in VB.NET. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Create DataView") adapter.Dispose() command.Dispose() connection.Close() dv = ds.Tables(0).DefaultView DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Sort DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price > 100", "Product_Price Desc",
DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open()
command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Filter DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price < = 500", "Product_Name", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand
adapter As New SqlDataAdapter ds As New DataSet dv As DataView sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Find Row DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_id").ToString() & " End If Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
We can add new rows in the DataView using AddNew method in the DataView. The following source code shows how to add new row in a DataView . Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Add New") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) Dim newRow As DataRowView = dv.AddNew() newRow("Product_ID") = 7 newRow("Product_Name") = "Product 7" newRow("Product_Price") = 111 newRow.EndEdit() dv.Sort = "product_id" DataGridView1.DataSource = dv
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Update")
adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_Name", DataViewRowState.CurrentRows) Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Product not found") Else dv(index)("Product_Name") = "Product11" MsgBox("Product Updated !") End If DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView
Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Delete Row") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_ID", DataViewRowState.CurrentRows) dv.Table.Rows(3).Delete() DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
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
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 .
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.
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
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.
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
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
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
vbc /t:library RemoteTime.vb vbc /r:RemoteTime.dll TimeListener.vb vbc /r:RemoteTime.dll Client.vb Note: You have to provide the physical path of each source files when you compile the source code , for example : if the source code files are in the folder c:\SRC , you have to give path like vbc /r:c:\SRC\RemoteTime.dll c:\SRC\TimeListener.vb After you complied the VB.Net source code files, you will get additional three files in the SRC folder. They are : RemoteTime.dll TimeListener.exe Client.exe To run the application Create two new folders and give the name like Server and Client respectively. Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the Server folder. Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder. Open a command prompt on Server folder and type TimeListener Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..." Open a command prompt on Client folder and type Client.
Then you will get the current time from remote Object. Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more on Remoting ...
Remoting Configurations
Configuration provides the necessary information to .Net Remoting Framework . We can provide .Net Remoting configuration parameters in two ways. Either we can provide the information to the Server and the Client directly by program coding or through a Machine.config file. Using configuration file give better advantage over coding because the parameters of remote object can be configured without changing any program coding and avoid recompile the source code. Following are the information provided by configuration file : Metadata describing the Remote Type Type of Activation Channels The URL that uniquely identifies the object of that type. We have to provide configuration information to Listener Object and also Client Object . Listener Configuration
Remoting Activation
The .Net Remoting framework supports Server and Client activation of Remote Objects. Before an Object instance of a Remotable type can be accessed, it must be created and initialized by Activation process. There are commonly two types of activation modes : Server Activation and Client Activation mode. Server activation is normally used when a Remote objects is not required to maintain any state between method calls. Client Activated objects are instantiated from the client, and the client manages the lifetime of the Remote Object by using a lease-based system provided for that purpose. SingleCall Objects and Singleton Objects belong to Server Activation mode. For SingleCall objects the server will create a single object, execute the method, and destroy the object again. On the other hand with Singleton mode only one object is created at all. Singleton objects can be used to share information between multiple clients. The real distinction between Client Activated and Server Activated object is that a server-activated object is not really created when a client instantiates it. Instead, it is created as needed.
Remoting Channel
In .Net Remoting Channels are used to transport messages to and from the Remote Objects. Channels are Objects that responsible of handling the network protocols and serialization formats. In .Net Remoting channel can be implement either by calling the method ChannelServices.RegisterChannel or by using configuration file. Channels should be registered before objects are registered. When a channel is registered, it automatically starts listening for client requests at the specified port. At least one channel must be registered with the remoting framework before a Remote object can be called. There are two types of Channels available in .Net Remote Framework: HTTP channel and TCP channel. The HTTP channel transports messages to and from remote objects using the SOAP protocol. The TCP channel uses a binary formatter to serialize all messages to a binary stream and transport the stream to the target URI using the TCP protocol.
Remoting Channel
Formatters are used for encoding and decoding the messages before they are transported by the Channel in .Net Remoting Framework. The .Net Remoting Framework supports two types of Formatters : Binary Formatter System.Runtime.Serialization.Formatters.Binary and SOAP Formatter - System.Runtime.Serialization.Formatters.Soap . The data in binary Formatter has smaller size when compared to SOAP Formatter. The SOAP Formatter is an XML based cross platform text format , so it can be human readable. The data in a SOAP Formatter larger size compared to Binary Formatter , so it can therefore reduce overall performance. VB.NET ADO.NET DATASET TUTORIALS
The Dataset contains the copy of the data we requested. The Dataset contains more than one Table at a time. We can set up Data Relations between these tables within the DataSet. The data set may comprise data for one or more members, corresponding to the number of rows.
The DataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method of the DataAdapter for populating data in a Dataset. The DataSet can be filled either from a data source or dynamically. A DataSet can be saved to an XML file and then loaded back into memory very easily. The following links shows more information of Dataset in details.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User
ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) adapter.Dispose() command.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -" & ds.Tables(0).Rows(i).Item(1))
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class -" & ds.Tables(0).Rows(i).Item(1))
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The Dataset may comprise data for one or more members, corresponding to the number of rows. The SqlDataAdapter object allows us to populate DataTables in a DataSet. In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset.
Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim tables As DataTable Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() For Each tables In ds.Tables MsgBox(tables.TableName)
Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here"
connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables.Count - 1 MsgBox(ds.Tables(i).TableName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
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
connection As SqlConnection command As SqlCommand adapter As New SqlDataAdapter ds As New DataSet sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() MsgBox("Number of row(s) " & ds.Tables(0).Rows.Count)
Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
The DataSet contains copy of the data we requested through the SQL statement. The DataSet consists of DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data inside Table is in the form of Rows and Columns . The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset from OLEDB Data Source. Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() MsgBox("number of Row(s) " & ds.Tables(0).Rows.Count)
Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here"
You have to replace the string with your real time variables.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim column As DataColumn Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table")
adapter.Dispose() command.Dispose() connection.Close() dt = ds.Tables(0) For Each column In dt.Columns MsgBox(column.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() dt = ds.Tables(0) For i = 0 To dt.Columns.Count - 1 MsgBox(dt.Columns(i).ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
more members, corresponding to the number of rows. We can fill the data in Dataset without calling SQL statements. For that we manually create a DataTable and add data in it.
Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim dt As DataTable Dim dr As DataRow Dim idCoulumn As DataColumn Dim nameCoulumn As DataColumn Dim i As Integer dt = New DataTable() idCoulumn = New DataColumn("ID", Type.GetType("System.Int32")) nameCoulumn = New DataColumn("Name", Type.GetType("System.String")) dt.Columns.Add(idCoulumn) dt.Columns.Add(nameCoulumn) dr = dt.NewRow() dr("ID") = 1 dr("Name") = "Name1" dt.Rows.Add(dr) dr = dt.NewRow() dr("ID") = 2 dr("Name") = "Name2" dt.Rows.Add(dr) ds.Tables.Add(dt) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next i End Sub -" & ds.Tables(0).Rows(i).Item(1))
End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "First Table")
adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Second Table") adapter.Dispose() command.Dispose() connection.Close() 'retrieve first table data For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " Next 'retrieve second table data For i = 0 To ds.Tables(1).Rows.Count - 1 MsgBox(ds.Tables(1).Rows(i).Item(0) & " Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
--
--
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(firstSql, connection) oledbAdapter.Fill(ds, "First Table") oledbAdapter.SelectCommand.CommandText = secondSql oledbAdapter.Fill(ds, "Second Table") oledbAdapter.Dispose() connection.Close() 'retrieve first table data For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " & ds.Tables(0).Rows(i).Item(1)) Next 'retrieve second table data For i = 0 To ds.Tables(1).Rows.Count - 1 MsgBox(ds.Tables(1).Rows(i).Item(0) & " -- " & ds.Tables(1).Rows(i).Item(1)) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table1") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table2")
adapter.Dispose() command.Dispose() connection.Close() 'creating data relations Dim relation As DataRelation Dim table1Column As DataColumn Dim table2Column As DataColumn 'retrieve column table1Column = ds.Tables("Table1").Columns(0) table2Column = ds.Tables("table2").Columns(0) 'relating tables relation = New DataRelation("relation", table1Column, table2Column) 'assign relation to dataset ds.Relations.Add(relation) MsgBox("Data relation completed") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.
In some situation we want to combine the result of multiple SQL query as a single result set. In that case we can use the Dataset's Merge method for doing this. The tables involved in the merge should be identical, that is the columns are similar data types .
Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table(0)") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table(1)") adapter.Dispose() command.Dispose() connection.Close() ds.Tables(0).Merge(ds.Tables(1)) dt = ds.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " Next -" & dt.Rows(i).Item(1))
Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds1 As New DataSet Dim ds2 As New DataSet Dim dt As DataTable Dim firstSql As String Dim secondSql As String Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(firstSql, connection) oledbAdapter.Fill(ds1, "First Table") oledbAdapter.SelectCommand.CommandText = secondSql oledbAdapter.Fill(ds2, "Second Table") oledbAdapter.Dispose() connection.Close() ds1.Tables(0).Merge(ds2.Tables(0)) dt = ds1.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " Next -" & dt.Rows(i).Item(1))
Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.
SQL Server that stores variable length binary data from 0 through 2A31-1 (2,147,483,647) bytes. The following VB.NET program shows how to insert an Image in SQL Server. First you have to create a table that contain an image column . The following sql script help you to create a table with Image Datatype column :
CREATE TABLE [dbo].[imgtable]( [id] [int] NULL, [img] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
The above scrip will create a table named as imgtable and adding two column , first column is id ,an integer datatype and second column is image, an image(img) datatype. The following VB.NET source code read the image from physical path D:\picfile.jpg and stores it to a byte array and then insert it into database. Download Source Code
Imports System.Data.SqlClient Imports System.IO Public Class Form1 Dim fName As String Dim cnn As SqlConnection Dim connectionString As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password" cnn = New SqlConnection(connectionString) fName = "D:\picfile.jpg" If File.Exists(fName) Then Dim id As Integer = 1 Dim content As Byte() = ImageToStream(fName) cnn.Open()
Dim cmd As New SqlCommand("insert into imgtable (id,img) values ( @id,@img)", cnn) cmd.Parameters.AddWithValue("@id", id) cmd.Parameters.AddWithValue("@img", content) cmd.ExecuteNonQuery() cnn.Close() MsgBox("Image inserted") Else MsgBox(fName & " not found ") End If End Sub Private Function ImageToStream(ByVal fileName As String) As Byte() Dim stream As New MemoryStream() tryagain: Try Dim image As New Bitmap(fileName) image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg) Catch ex As Exception GoTo tryagain End Try Return Stream.ToArray() End Function End Class
The following VB.NET source code shows how to retrieve an image from SQL Server. Download Source Code
Imports System.IO Imports System.Data.SqlClient Public Class Form1 Dim cnn As SqlConnection Dim connectionString As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password" cnn = New SqlConnection(connectionString) Dim stream As New MemoryStream() cnn.Open() Dim command As New SqlCommand("select img from imgtable where id=1", cnn) Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte()) stream.Write(image, 0, image.Length) cnn.Close() Dim bitmap As New Bitmap(stream) PictureBox1.Image = bitmap End Sub End Class
The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . These classes are stored in the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal storage format. You can use any text editor to create an XML file . More over XML files are readable by humans as well as computers. From the following links you can see how to use XML in VB.NET.
Working Effectively with Legacy Code Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more... Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim writer As New XmlTextWriter("product.xml", System.Text.Encoding.UTF8) writer.WriteStartDocument(True) writer.Formatting = Formatting.Indented writer.Indentation = 2 writer.WriteStartElement("Table") createNode(1, "Product 1", "1000", writer) createNode(2, "Product 2", "2000", writer) createNode(3, "Product 3", "3000", writer) createNode(4, "Product 4", "4000", writer) writer.WriteEndElement() writer.WriteEndDocument() writer.Close() End Sub Private Sub createNode(ByVal pID As String, ByVal pName As String, ByVal pPrice As String, ByVal writer As XmlTextWriter)
writer.WriteStartElement("Product") writer.WriteStartElement("Product_id") writer.WriteString(pID) writer.WriteEndElement() writer.WriteStartElement("Product_name") writer.WriteString(pName) writer.WriteEndElement() writer.WriteStartElement("Product_price") writer.WriteString(pPrice) writer.WriteEndElement() writer.WriteEndElement() End Sub End Class
XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the information embedded in XML tags in an XML file. In the previous program we create an XML file and named it as products.xml. The following program read that file and extract the contents inside the XML tag. We can read an XML file in several ways depends on our requirement. This program read the content in Node wise . Here we are using XmlDataDocument class to read the XML file . In this program it search the Node < Product > and its child Nodes and extract the data in child nodes.
Download Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms spreadsheet controls, Excel compatible charting, the fastest and most complete Excel compatible calculations and more Print Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
Imports System.Xml Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmldoc As New XmlDataDocument() Dim xmlnode As XmlNodeList Dim i As Integer Dim str As String Dim fs As New FileStream("products.xml", FileMode.Open, FileAccess.Read) xmldoc.Load(fs) xmlnode = xmldoc.GetElementsByTagName("Product") For i = 0 To xmlnode.Count - 1 xmlnode(i).ChildNodes.Item(0).InnerText.Trim() str = xmlnode(i).ChildNodes.Item(0).InnerText.Trim() & " | " & xmlnode(i).ChildNodes.Item(1).InnerText.Trim() & " | " & xmlnode(i).ChildNodes.Item(2).InnerText.Trim() MsgBox(str) Next End Sub End Class
Print Source Code SpreadsheetGear: ASP.NET Excel Reporting Easily create richly formatted Excel reports without Excel using the new generation of spreadsheet technology built from the ground up for scalability and reliability. Learn more
Imports System.Data Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet dt = New DataTable() dt.Columns.Add(New DataColumn("Product_ID", Type.GetType("System.Int32"))) dt.Columns.Add(New DataColumn("Product_Name", Type.GetType("System.String"))) dt.Columns.Add(New DataColumn("product_Price", Type.GetType("System.Int32"))) fillRows(1, "product1", 1111) fillRows(2, "product2", 2222) fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" ds.WriteXml("Product.xml") MsgBox("Done") End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class
In the previous section we already saw how to read an XML file through Node navigation . Here we are going to read an XML file using an DataSet. Here Dataset is using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. Click here to download the input file product.xml
Download Source Code SpreadsheetGear: ASP.NET Excel Reporting Easily create richly formatted Excel reports without Excel using the new generation of spreadsheet technology built from the ground up for scalability and reliability. Learn more Print Source Code The Android Developer's Cookbook Want to get started building applications for Android? Already building Android applications and want to get better at it? This book brings together all the expert guidanceand codeyoull need!
Imports System.Xml Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) Dim i As Integer For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next End Sub End Class
There are several ways to create an XML file . In the previous sections we already saw how to create an XML file using XmlTextWriter and also created an XML file using manually created Dataset. Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as argument.
Download Source Code SpreadsheetGear for ASP.NET and WinForms Excel Reporting, dashboards from Excel charts and ranges, Windows Forms spreadsheet controls, Excel compatible charting, the fastest and most complete Excel compatible calculations and more Print Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.
Imports System.Xml Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(sql, connection) adapter.Fill(ds) connection.Close() ds.WriteXml("Product.xml") MsgBox("Done") Catch ex As Exception MsgBox(ex.ToString) End Try
MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_Name").ToString() & " End If End Sub " & dv(index)("Product_Price").ToString())
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView
ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0), "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows) dv.ToTable().WriteXml("Result.xml") MsgBox("Done") End Sub End Class
Imports System.Xml Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String
connection As SqlConnection command As SqlCommand adpter As New SqlDataAdapter ds As New DataSet xmlFile As XmlReader sql As String
Dim product_ID As Integer Dim Product_Name As String Dim product_Price As Double connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString) xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile) Dim i As Integer connection.Open() For i = 0 To ds.Tables(0).Rows.Count - 1 product_ID = Convert.ToInt32(ds.Tables(0).Rows(i).Item(0)) Product_Name = ds.Tables(0).Rows(i).Item(1) product_Price = Convert.ToDouble(ds.Tables(0).Rows(i).Item(2)) sql = "insert into Product values(" & product_ID & ",'" & Product_Name & "'," & product_Price & ")" command = New SqlCommand(sql, connection) adpter.InsertCommand = command adpter.InsertCommand.ExecuteNonQuery() Next connection.Close() End Sub End Class
You have to pass necessary database connection information to connection string. Click here to download the input file product.xml
XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify what the data it contains. Here we are going to read from an XML file content and write the same content to an Excel file. Using an XmlReader for read the XML file to the Dataset . Loop through the Dataset and add the content to the Excel file . For create an excel file you have to add reference of Excel library to you project .
Download Source Code Print Source Code
Introducing HTML5 (Voices that Matter) Take our 3-Minute Hosting Decisions Survey Concentrating on the practical and the issues that HTML5 can solve Participants will be eligible to win a $100 Amazon gift certificate. Take "Introducing HTML5" is written by developers who have been using the the short survey here. new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
Imports System.Xml Imports System.Data Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim ds As New DataSet Dim xmlFile As XmlReader Dim i, j As Integer xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile)
For i = 0 To ds.Tables(0).Rows.Count - 1 For j = 0 To ds.Tables(0).Columns.Count - 1 xlWorkSheet.Cells(i + 1, j + 1) = _ ds.Tables(0).Rows(i).Item(j) Next Next xlWorkSheet.SaveAs("xml2excel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub End Class
The following program shows how to create an XML file from an Excel file content . Here we are using an OleDbConnection to read the excel file and store the content to a Dataset . Call the method WriteXml of Datset to write to the XML file.
Download Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details Print Source Code C Programming Language (2nd Edition) The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures. More Details.
Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim MyConnection As System.Data.OleDb.OleDbConnection Dim ds As System.Data.DataSet Dim MyCommand As System.Data.OleDb.OleDbDataAdapter MyConnection = New System.Data.OleDb.OleDbConnection _ ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='xl2xml.xls';Extended Properties=Excel 8.0;") MyCommand = New System.Data.OleDb.OleDbDataAdapter _ ("select * from [Sheet1$]", MyConnection) MyCommand.TableMappings.Add("Table", "Product") ds = New System.Data.DataSet MyCommand.Fill(ds) MyConnection.Close() ds.WriteXml("Product.xml") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
XML is a platform independent language, so the information formatted in XML file can be use in any other platforms . The .Net technology is widely supported XML file format. The following source code shows , how to load data in a DataGridView from an XML file . Here the Dataset using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. When the Dataset retrieves the data, it passes as DataSource to DataGridView .
Download Source Code Professional Code Generator Free for personal usage Ensure rock-solid foundations for your application while focusing on features, not plumbing. ASP.NET, Silverlight, WPF, Winforms, Phone or Azure. Print Source Code Introducing HTML5 (Voices that Matter) Concentrating on the practical and the issues that HTML5 can solve "Introducing HTML5" is written by developers who have been using the new language for the past year in their work, this book shows you how to start adapting the language now to realize its benefits on today's browsers. More Details
Imports System.Xml Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) DataGridView1.DataSource = ds.Tables(0) End Sub End Class
In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes data to TreeView.
Download Source Code Download Free CMS for ASP.NET Easily develop websites, intranets, social networks and e-shops. Download Now! Print Source Code Professional Code Generator Free for personal usage Ensure rock-solid foundations for your application while focusing on features, not plumbing. ASP.NET, Silverlight, WPF, Winforms, Phone or Azure.
Imports System.Xml Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmldoc As New XmlDataDocument() Dim xmlnode As XmlNode
Dim fs As New FileStream("tree.xml", FileMode.Open, FileAccess.Read) xmldoc.Load(fs) xmlnode = xmldoc.ChildNodes(1) TreeView1.Nodes.Clear() TreeView1.Nodes.Add(New TreeNode(xmldoc.DocumentElement.Name)) Dim tNode As TreeNode tNode = TreeView1.Nodes(0) AddNode(xmlnode, tNode) End Sub Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As TreeNode) Dim xNode As XmlNode Dim tNode As TreeNode Dim nodeList As XmlNodeList Dim i As Integer If inXmlNode.HasChildNodes Then nodeList = inXmlNode.ChildNodes For i = 0 To nodeList.Count - 1 xNode = inXmlNode.ChildNodes(i) inTreeNode.Nodes.Add(New TreeNode(xNode.Name)) tNode = inTreeNode.Nodes(i) AddNode(xNode, tNode) Next Else inTreeNode.Text = inXmlNode.InnerText.ToString End If End Sub End Class
The basics of Crystal Reports creation provided in previous tutorials , if you dont have much knowledge in Crystal Reports , take a look at the tutorial step by step Crystal Report before start this section. The change happen only from previous report , when you select Data for Crsyatl Report , you have to select Create New Connection Database Files and select the XML file you want to generate Crystal Reports (In this case you select the Product.xml ).
Select all the fields from Product and click finish button Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program .
Download Source Code Print Source Code
Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here.
The following program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer class for serialize the Dataset Object.
Download Source Code Print Source Code
Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet dt = New DataTable() dt.Columns.Add(New DataColumn("Product_ID", Type.GetType("System.Int32"))) dt.Columns.Add(New DataColumn("Product_Name", Type.GetType("System.String"))) dt.Columns.Add(New DataColumn("product_Price", Type.GetType("System.Int32"))) fillRows(1, "product1", 9999) fillRows(2, "product2", 2222) fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" Dim serialWriter As StreamWriter serialWriter = New StreamWriter("serialXML.xml") Dim xmlWriter As New XmlSerializer(ds.GetType()) xmlWriter.Serialize(serialWriter, ds) serialWriter.Close() ds.Clear() End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class
<DataSet><xs:schema xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema" id="NewDataSet"><xs:element msdata:UseCurrentLocale="true" msdata:IsDataSet="true" name="NewDataSet"><xs:complexType><xs:choice maxOccurs="unbounded" minOccurs="0"><xs:element name="product"><xs:complexType><xs:sequence><xs:element type="xs:int" name="Product_ID" minOccurs="0"/><xs:element type="xs:string" name="Product_Name" minOccurs="0"/><xs:element type="xs:int" name="product_Price" minOccurs="0"/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xmldiffgram-v1"><NewDataSet><product diffgr:id="product1" diffgr:hasChanges="inserted" msdata:rowOrder="0"><Product_ID>1</Product_ID><Product_Name>product1</Product_Name><product_Price>9999</p roduct_Price></product><product diffgr:id="product2" diffgr:hasChanges="inserted" msdata:rowOrder="1"><Product_ID>2</Product_ID><Product_Name>product2</Product_Name><product_Price>2222</p roduct_Price></product><product diffgr:id="product3" diffgr:hasChanges="inserted" msdata:rowOrder="2"><Product_ID>3</Product_ID><Product_Name>product3</Product_Name><product_Price>3333</p roduct_Price></product><product diffgr:id="product4" diffgr:hasChanges="inserted" msdata:rowOrder="3"><Product_ID>4</Product_ID><Product_Name>product4</Product_Name><product_Price>4444</p roduct_Price></product></NewDataSet></diffgr:diffgram></DataSet>
Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class
The following lessons explain the basics of DataGridView control and steps through an example that builds simple vb.net programs. All the source code in the following examples ,we chose the Pubs database, which comes with SQL Server , as our target database.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class
source. When you specify a data source for the DataGridView, by default it will construct columns for you automatically. This will be created based on the data types in the data source. The following vb.net program shows how to bind an OLEDB dataset in a DataGridView. Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Your .mdb path";" Dim sql As String = "SELECT * FROM Authors" Dim connection As New OleDbConnection(connectionString) Dim dataadapter As New OleDbDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Titles" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Titles_table") connection.Close() Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).Visible = False End Sub End Class
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
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
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
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
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
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
The DataGridView class allows customization of cells, rows, columns, and borders through the use of its properties . If a DataGridView has lot of rows then we can implement paging functionalities to the DataGridView control. While we implement paging we should know the boundaries of the pages to enable the paging in the DatagridView. The following vb.net program provides a way to programmatically implement paging in a Windows Datagrid View control. Here the DataGridView rows fixed as five rows and other two buttons are there for implementing paging functionalities. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Dim pagingAdapter As SqlDataAdapter Dim pagingDS As DataSet Dim scrollVal As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM authors" Dim connection As New SqlConnection(connectionString) pagingAdapter = New SqlDataAdapter(sql, connection) pagingDS = New DataSet() connection.Open() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") connection.Close() DataGridView1.DataSource = pagingDS DataGridView1.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click scrollVal = scrollVal - 5 If scrollVal <= 0 Then scrollVal = 0 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub End Class
The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. Typically, however, multiple cells will share particular style characteristics. You can define appearance and formatting styles for individual cells, for cells in specific columns and rows, or for all cells in the control by setting the properties of the DataGridViewCellStyle objects accessed through various DataGridView control properties. The following vb.net program shows how to implement different ways of cell formatting in a DataGridView control. Download Source Code
Imports System.Data.SqlClient
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" DataGridView1.GridColor = Color.Red DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None DataGridView1.BackgroundColor = Color.LightGray DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True] DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect DataGridView1.AllowUserToResizeColumns = False DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End Sub End Class
There are situations that you want greater control over the appearance of DataGridView rows than what is provided by the various DataGridView cell style properties. The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set any DataGridViewRow properties, including DefaultCellStyle. When displaying external data, however, the rows are generated automatically, but they are based on the row template, which you can set to an instance of your custom row type. The following vb.net code example illustrates how to use the row template to specify an initial row height and a minimum row height and BackColor. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click Dim row As DataGridViewRow = Me.DataGridView1.RowTemplate row.DefaultCellStyle.BackColor = Color.Bisque row.Height = 35 row.MinimumHeight = 20 Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class
The DataGridView control provides a customizable table for displaying data. It gives you number of properties, methods and events to customize its appearance and behavior. Unfortunately the DataGridView doesn't have a built in printing functionality . So here we do a tricky way to print the content of DataGridView . Here we add a PrintDocument object to the project and handle the PrintPage event which is called every time a new page is to be printed. Here in the PrintPage event we create a Bitmap Object and draw the DataGridView to the Bitmap Object. In order to run this vb.net project you have to drag two buttons ,one for load data and one for print command, and drag a PrintDocument control on your form . The following picture shows how to drag PrintDocument Object to your project. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim bm As New Bitmap(Me.DataGridView1.Width, Me.DataGridView1.Height) DataGridView1.DrawToBitmap(bm, New Rectangle(0, 0, Me.DataGridView1.Width, Me.DataGridView1.Height)) e.Graphics.DrawImage(bm, 0, 0) End Sub End Class
Imports System.Data.SqlClient Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Int16, j As Int16 xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") For i = 0 To DataGridView1.RowCount - 2 For j = 0 To DataGridView1.ColumnCount - 1 xlWorkSheet.Cells(i + 1, j + 1) = DataGridView1(j, i).Value.ToString() Next Next
xlWorkBook.SaveAs("c:\vb.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _ Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue) xlWorkBook.Close(True, misValue, misValue) xlApp.Quit() releaseObject(xlWorkSheet) releaseObject(xlWorkBook) releaseObject(xlApp) MessageBox.Show("Over") End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing MessageBox.Show("Exception Occured while releasing object " + ex.ToString()) Finally GC.Collect() End Try End Sub End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim MyConnection As System.Data.OleDb.OleDbConnection Dim DtSet As System.Data.DataSet Dim MyCommand As System.Data.OleDb.OleDbDataAdapter MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;") MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection) MyCommand.TableMappings.Add("Table", "Net-informations.com") DtSet = New System.Data.DataSet MyCommand.Fill(DtSet) DataGridView1.DataSource = DtSet.Tables(0) MyConnection.Close() End Sub End Class
The DataGridView control can display rows of data from a data source. The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain. The following vb.net source code illustrate how to connect a DataGridView to a database and addnew/update or delete the database values from DataGridView. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Dim sCommand As SqlCommand
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Stores" Dim connection As New SqlConnection(connectionString) connection.Open() sCommand = New SqlCommand(sql, connection) sAdapter = New SqlDataAdapter(sCommand) sBuilder = New SqlCommandBuilder(sAdapter) sDs = New DataSet() sAdapter.Fill(sDs, "Stores") sTable = sDs.Tables("Stores") connection.Close() DataGridView1.DataSource = sDs.Tables("Stores") DataGridView1.ReadOnly = True save_btn.Enabled = False DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect End Sub Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click DataGridView1.[ReadOnly] = False save_btn.Enabled = True new_btn.Enabled = False delete_btn.Enabled = False End Sub Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index) sAdapter.Update(sTable) End If End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click sAdapter.Update(sTable) DataGridView1.[ReadOnly] = True save_btn.Enabled = False new_btn.Enabled = True delete_btn.Enabled = True End Sub End Class