Vous êtes sur la page 1sur 136

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;"

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.

ADO.NET ExecuteNonQuery in SqlCommand Object


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

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

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here"

ADO.NET ExecuteScalar in SqlCommand Object


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

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

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here like Select Count(*) from product"

ADO.NET ExecuteReader in SqlCommand Object


ExecuteReader() in SqlCommand Object send the SQL statements to Connection Object and populate a SqlDataReader Object based on the SQL statement. When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object.

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

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

How to ADO.NET DataReader


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

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

How to ADO.NET SqlDataReader


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

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " " & sqlReader.Item(2)) 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"

How to Multiple Result Sets in ADO.NET


The DataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() In some situations we need to pass multiple SQL statements to the Command Object. In this situations the SqlDataReader returns multiple ResultSets also. For retrieveing multiple ResultSets from SqlDataReader we use the NextResult() method of the SqlDataReader. SqlDataReader.NextResult() In the following source code demonstrating how to get multiple result sets from SqlDataReader() . Download Source Code Print Source Code

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

" &

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"

Schema Informations from SqlDataReader


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

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim 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 * 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"

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.

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) & " ds.Tables(0).Rows(i).Item(1)) 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"

Vb.NET ExecuteReader and ExecuteNonQuery


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

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

Stored Procedures in VB.NET


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

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

From the following source code you can see how to call a stored procedure from VB.NET application. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(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 command As New SqlCommand Dim ds As New DataSet

Print Source Code

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

Stored Procedure with Parameter


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

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

command.Parameters.Add(param)

The above code passing country parameter to the stored procedure from vb.net. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim command As New SqlCommand Dim param As SqlParameter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPCOUNTRY" param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String command.Parameters.Add(param) adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class

Print Source Code

VB.NET Implicit and Explicit Conversions


Implicit Type Conversions Implicit Conversion perform automatically in VB.NET, that is the compiler is taking care of the conversion.

The following example you can see how it happen. 1. Dim iDbl As Double 2. Dim iInt As Integer 3. iDbl = 9.123 4. MsgBox("The value of iDbl is " iDbl) 5. iInt = iDbl 6. MsgBox("The value of iInt is " iInt) line no 1 : Declare a Double datatype variable iDble line no 2 : Declare an Integer datatyoe variable iInt line no 3 : Assign a decimal value to iDbl line no 4 : Display the value of iDbl line no 5 : Assign the value of iDbl to iInt line no 6 : Display the value of iInt The first messagebox display the value of iDbl is 9.123 The second messegebox display the value od iInt is 9 iInt display only 9 because the value is narrowed to 9 to fit in an Integer variable. Here the Compiler made the conversion for us. These type fo conversions are called Implicit Conversion . The Implicit Conversion perform only when the Option Strict switch is OFF Download Source Code Print Source Code

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

'after conversion MsgBox("The value of iInt is " & iInt) End Sub End Class

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

How to VB.NET Access Specifiers


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

How to VB.NET Exceptions


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

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

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

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

Dim i As Integer Dim resultValue As Integer i = 100 resultValue = i / 0 MsgBox("The result is " & resultValue) Catch ex As Exception MsgBox("Exception catch here ..") Finally MsgBox("Finally block executed ") End Try End Sub End Class

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

VB.NET Option Explicit [On | Off]


Option Explicit statement ensures whether the compiler requires all variables to be explicitly declared or not before it use in the program. Option Explicit [On Off] The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON , you have to declare all the variable before you use it in the program . If not , it will generate a compile-time error whenever a variable that has not been declared is encountered .If the Option Explicit mode is OFF , Vb.Net automatically create a variable whenever it sees a variable without proper declaration. By default the Option Explicit is On With the Option Explicit On , you can reduce the possible errors that result from misspelled variable names. Because in Option Explicit On mode you have to declare each variable in the program for storing data. Take a look at the following programs, it will give you a clear picture of Option Explicit. The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The default is Option Explicit On , so we do not need to put it in the source code. VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim someVariable As String someVariable = "Option Explicit ON"

MsgBox(someVariable) End Sub End Class

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

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

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

VB.NET Option Strict [On | Off]


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

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

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

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

VB.NET On Error GoTo


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

Dim num As Integer num = 100 result = num / 0 MsgBox("here") End Sub End Class

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

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

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

Label Control
Microsoft Visual Studio .NET controls are the graphical tools you use to build the user interface of a VB.Net program. Labels are one of the most frequently used Visual Basic control. A Label control lets you place descriptive text , where the text does not need to be changed by the user. The Label class is defined in the System.Windows.Forms namespace.

Add a Label control to the form. Click Label in the Toolbox and drag it over the forms Designer and drop it in the desired location.

If you want to change the display text of the Label, you have to set a new text to the Text property of Label.
Label1.Text = "This is my first Label"

You can load Image in Label control , if you want to load an Image in the Lable control you can code like this
Label1.Image = Image.FromFile("C:\testimage.jpg")

The following source code shows how to set some properties of the Label through coding. Download Source Code Print Source Code

Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Label1.Text = "This is my first Label" Label1.BorderStyle = BorderStyle.FixedSingle Label1.TextAlign = ContentAlignment.MiddleCenter End Sub

Button Control
Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client side Windows applications. A Button is a control, which is an interactive component that enables users to communicate with an application which we click and release to perform some actions.

The Button control represents a standard button that reacts to a Click event. A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button has focus. When you want to change display text of the Button , you can change the Text property of the button.
Button1.Text = "My first Button"

Similarly if you want to load an Image to a Button control , you can code like this
Button1.Image = Image.FromFile("C:\testimage.jpg")

The following vb.net source code shows how to change the button Text property while Form loading event and to display a message box when pressing a Button Control. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Button1.Text = "Click Here" End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MsgBox("http://vb.net-informations.com") End Sub End Class

Print Source Code

TextBox Control
VB.Net provides several mechanisms for gathering input in a program. A TextBox control is used to display, or accept as input, a single line of text.

VB.Net programmers make extensive use of the TextBox control to let the user view or enter large amount of text. A text box object is used to display text on a form or to get user input while a VB.Net program is running. In a text box, a user can type data or paste it into the control from the clipboard. For displaying a text in a TextBox control , you can code like this
TextBox1.Text = "http://vb.net-informations.com"

You can also collect the input value from a TextBox control to a variable like this way
Dim var As String var = TextBox1.Text

when a program wants to prevent a user from changing the text that appears in a text box, the program can set the controls Readonly property is to True.
TextBox1.ReadOnly = True

By default TextBox accept single line of characters , If you need to enter more than one line in a TextBox control, you should change the Multiline property is to True.
TextBox1.Multiline = True

Sometimes you want a textbox to receive password from the user. In order to keep the password confidential, you can set the PasswordChar property of a textbox to a specific character.

TextBox1.PasswordChar = "*"

The above code set the PasswordChar to * , so when the user enter password then it display only * instead of other characters. From the following VB.Net source code you can see some important property settings to a TextBox control. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Width = 200 TextBox1.Height = 50 TextBox1.Multiline = True End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As String var = TextBox1.Text MsgBox(var) End Sub End Class

Print Source Code

ComboBox Control
VB.Net controls are located in the Toolbox of the development environment, and you use them to create objects on a form with a simple series of mouse clicks and dragging motions. The ComboBox control , which lets the user choose one of several choices.

The user can type a value in the text field or click the button to display a drop down list. In addition to display and selection functionality, the ComboBox also provides features that enable you to efficiently add items to the ComboBox.
ComboBox1.Items.Add("Sunday")

You can set which item should shown while it displaying in the form for first time.
ComboBox1.SelectedItem = ComboBox1.Items(3)

When you run the above code it will show the forth item in the combobox. The item index is starting from 0. If you want to retrieve the displayed item to a string variable , you can code like this
Dim var As String var = ComboBox1.Text

You can remove items from a combobox in two ways. You can remove item at a the specified index or giving a specified item by name.
ComboBox1.Items.RemoveAt(1)

The above code will remove the second item from the combobox.
ComboBox1.Items.Remove("Friday")

The above code will remove the item "Friday" from the combobox. The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop down. The DropDownStyle property also specifies whether the text portion can be edited.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDown

The following VB.Net source code add seven days in a week to a combo box while load event of a Windows Form and display the fourth item in the combobox. Download Source Code Print Source Code

Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ComboBox1.Items.Add("Sunday") ComboBox1.Items.Add("Monday") ComboBox1.Items.Add("Tuesday") ComboBox1.Items.Add("wednesday") ComboBox1.Items.Add("Thursday") ComboBox1.Items.Add("Friday") ComboBox1.Items.Add("Saturday") ComboBox1.SelectedItem = ComboBox1.Items(3) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As String var = ComboBox1.Text MsgBox(var) End Sub End Class

ListBox Control
VB.Net provides several mechanisms for gathering input in a program. A Windows Forms ListBox control displays a list of choices which the user can select from.

You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box. The Insert method allows you to specify where to insert the item you are adding.
ListBox1.Items.Add("Sunday")

The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or multiple selections using the SelectionMode property . If you want to retrieve a single selected item to a variable , you can code like this
Dim var As String var = ListBox1.SelectedItem

If you change the selection mode property to multiple select , then you will retrieve a collection of items from ListBox1.SelectedItems property.
ListBox1.SelectionMode = SelectionMode.MultiSimple

The following VB.Net program initially fill seven days in a week while in the form load event and set the selection mode property to MultiSimple. At the Button click event it will display the selected items. Download Source Code Print Source Code

Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListBox1.Items.Add("Sunday") ListBox1.Items.Add("Monday") ListBox1.Items.Add("Tuesday") ListBox1.Items.Add("Wednesday") ListBox1.Items.Add("Thursday") ListBox1.Items.Add("Friday") ListBox1.Items.Add("Saturday") ListBox1.SelectionMode = SelectionMode.MultiSimple End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim obj As Object For Each obj In ListBox1.SelectedItems MsgBox(obj.ToString) Next End Sub End Class

Checked ListBox Control


The CheckedListBox control gives you all the capability of a list box and also allows you to display a check mark next to the items in the list box.

To add objects to the list at run time, assign an array of object references with the AddRange method. The list then displays the default string value for each object.
Dim days As String() = {"Sunday", "Monday", "Tuesday"}

checkedListBox1.Items.AddRange(days)

You can add individual items to the list with the Add method. The CheckedListBox object supports three states through the CheckState enumeration: Checked, Indeterminate, and Unchecked.
CheckedListBox1.Items.Add("Sunday", CheckState.Checked) CheckedListBox1.Items.Add("Monday", CheckState.Unchecked) CheckedListBox1.Items.Add("Tuesday", CheckState.Indeterminate)

Download Source Code


Public Class Form1

Print Source Code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load CheckedListBox1.Items.Add("Sunday", CheckState.Checked) CheckedListBox1.Items.Add("Monday", CheckState.Unchecked) CheckedListBox1.Items.Add("Tuesday", CheckState.Indeterminate) CheckedListBox1.Items.Add("Wednesday", CheckState.Checked) CheckedListBox1.Items.Add("Thursday", CheckState.Unchecked) CheckedListBox1.Items.Add("Friday", CheckState.Indeterminate) CheckedListBox1.Items.Add("Saturday", CheckState.Indeterminate) End Sub End Class

RadioButton Control
A radio button or option button is a type of graphical user interface element that allows the user to choose only one of a predefined set of options. When a user clicks on a radio button, it becomes checked, and all other radio buttons with same group become unchecked

The radio button and the check box are used for different functions. Use a radio button when you want the user to choose only one option. When you want the user to choose all appropriate options, use a check box. Like check boxes, radio buttons support a Checked property that indicates whether the radio button is selected. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load RadioButton1.Checked = True End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If RadioButton1.Checked = True Then MsgBox("You are selected Red !! ") Exit Sub ElseIf RadioButton2.Checked = True Then MsgBox("You are selected Blue !! ") Exit Sub Else MsgBox("You are selected Green !! ") Exit Sub End If End Sub End Class

Print Source Code

CheckBox Control
CheckBoxes allow the user to make multiple selections from a number of options. You can click a check box to select it and click it again to deselect it.

CheckBoxes comes with a caption, which you can set in the Text property.
CheckBox1.Text = "Net-informations.com"

You can use the CheckBox control ThreeState property to direct the control to return the Checked, Unchecked, and Indeterminate values. You need to set the check boxs ThreeState property to True to indicate that you want it to support three states.
CheckBox1.ThreeState = True

To apply the same property settings to multiple CheckBox controls, use the Style property. The following VB.Net program shows how to find a checkbox is selected or not. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim msg As String = ""

Print Source Code

If CheckBox1.Checked = True Then msg = "net-informations.com" End If If CheckBox2.Checked = True Then msg = msg & " vb.net-informations.com" End If If CheckBox3.Checked = True Then msg = msg & " csharp.net-informations.com" End If If msg.Length > 0 Then MsgBox(msg & " selected ") Else MsgBox("No checkbox selected") End If CheckBox1.ThreeState = True End Sub End Class

PictureBox Control
The Windows Forms PictureBox control is used to display images in bitmap, GIF,icon, or JPEG formats.

You can set the Image property to the Image you want to display, either at design time or at run time. You can programmatically change the image displayed in a picture box, which is particularly useful when you use a single form to display different pieces of information.
PictureBox1.Image = Image.FromFile("C:\testImage.jpg")

The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration, controls the clipping and positioning of the image in the display area.
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage

There are five different PictureBoxSizeMode is available to PictureBox control.


AutoSize CenterImage Normal - Sizes the picture box to the image. - Centers the image in the picture box. - Places the upper-left corner of the image at upper left in the picture box

StretchImage - Allows you to stretch the image in code

You can change the size of the display area at run time with the ClientSize property.
pictureBox1.ClientSize = New Size(xSize, ySize)

The following VB.Net program shows how to load a picture from a file and display it in streach mode. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Image = Image.FromFile("d:\testImage.jpg") PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage End Sub End Class

Print Source Code

ScrollBars Control
The horizontal and vertical scrollbars which the user can use to move content into view.

Most of the controls that use scrollbars come with them built in, such as multiline text boxes, combo boxes etc. You can set the Value property yourself in code, which moves the scroll box to match. The controls Value property gets and sets its current numeric value. The Minimum and Maximum properties determine the range of values that the control can display. The following VB.Net program shows a TextBox control with scrollbars. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Multiline = True TextBox1.ScrollBars = ScrollBars.Both End Sub End Class

Print Source Code

ListView Control
List views displays a collection of items that can be displayed using one of five different views, such as LargeIcon, Details , SmallIcon, List and Tile.

ListView provides a large number of properties that provide flexibility in appearance and behavior. The View property allows you to change the way in which items are displayed. and the SelectionMode property determines how many items in the list can be selected at a time. The following Vb.Net program first set its view property as Details and GridLines property as true and FullRowSelect as true.
ListView1.View = View.Details ListView1.GridLines = True ListView1.FullRowSelect = True

After that it fills column header and then the column values.
ListView1.Columns.Add("ProductName", 100)

Finally in the button click event, it will display the selected row values in a message box. Download Source Code Print Source Code

Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ''Set view property ListView1.View = View.Details ListView1.GridLines = True ListView1.FullRowSelect = True 'Add column header ListView1.Columns.Add("ProductName", 100) ListView1.Columns.Add("Price", 70) ListView1.Columns.Add("Quantity", 70) 'Add items in the listview Dim arr(3) As String Dim itm As ListViewItem 'Add first item arr(0) = "product_1" arr(1) = "100" arr(2) = "10" itm = New ListViewItem(arr) ListView1.Items.Add(itm) 'Add second item arr(0) = "product_2" arr(1) = "200" arr(2) = "20" itm = New ListViewItem(arr) ListView1.Items.Add(itm) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim productName As String Dim price As String Dim quantity As String productName = ListView1.SelectedItems.Item(0).SubItems(0).Text price = ListView1.SelectedItems.Item(0).SubItems(1).Text quantity = ListView1.SelectedItems.Item(0).SubItems(2).Text MsgBox(productName & " , " & price & " , " & quantity) End Sub End Class

MDI Form
A Multiple Document Interface (MDI) programs can display multiple child windows inside them.

This is in contrast to single document interface (SDI) applications, which can manipulate only one document at a time. Visual Studio Environment is an example of Multiple Document Interface (MDI) and notepad is an example of an SDI application, opening a document closes any previously opened document. Any windows can become an MDI parent, if you set the IsMdiContainer property to True.
IsMdiContainer = True

The following vb.net program shows a MDI form with two child forms. Create a new VB.Net project, then you will get a default form Form1 . Then add two mnore forms in the project (Form2 , Form 3) . Create a Menu on your form and call these two forms on menu click event. Click the following link to see how to create a Menu on your form How to Menu Control VB.Net. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load IsMdiContainer = True End Sub Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

Print Source Code

MenuItem1ToolStripMenuItem.Click Dim frm2 As New Form2 frm2.Show() frm2.MdiParent = Me End Sub Private Sub MenuItem2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2ToolStripMenuItem.Click Dim frm3 As New Form3 frm3.Show() frm3.MdiParent = Me End Sub End Class

How to VB.NET ArrayList


ArrayList is one of the most flixible data structure from VB.NET Collections. ArrayList contains a simple list of values and very easily we can add , insert , delete , view etc.. to do with ArrayList. It is very flexible becuse we can add without any size information , that is it grow dynamically and also shrink . Important functions in ArrayList Add : Add an Item in an ArrayList Insert : Insert an Item in a specified position in an ArrayList Remove : Remove an Item from ArrayList RemoveAt: remeove an item from a specified position Sort : Sort Items in an ArrayList How to add an Item in an ArrayList ? Syntax : ArrayList.add(Item) Item : The Item to be add the ArrayList Dim ItemList As New ArrayList() ItemList.Add("Item4") How to Insert an Item in an ArrayList ? Syntax : ArrayList.insert(index,item)

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

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim ItemList As New ArrayList() ItemList.Add("Item4") ItemList.Add("Item5") ItemList.Add("Item2") ItemList.Add("Item1") ItemList.Add("Item3") MsgBox("Shows Added Items") For i = 0 To ItemList.Count - 1 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 index ItemList.RemoveAt(3) MsgBox("Shows final Items the ArrayList") For i = 0 To ItemList.Count - 1 MsgBox(ItemList.Item(i)) Next End Sub End Class

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

How to VB.Net HashTable


HashTable stores a Key Value pair type collection of data . We can retrive items from hashTable to provide the key . Both key and value are Objects. The common functions using in Hashtable are : Add : To add a pair of value in HashTable Syntax : HashTable.Add(Key,Value) Key : The Key value Value : The value of corrosponding key ContainsKey : Check if a specified key exist or not Synatx : HashTable.ContainsKey(key) Key : The Key value for search in HahTable ContainsValue : Check the specified Value exist in HashTable Synatx : HashTable.ContainsValue(Value) Value : Search the specified Value in HashTable Remove : Remove the specified Key and corrosponding Value Syntax : HashTable.Remove(Key) Key : The argument key of deleting pairs

The following source code shows all important operations in a HashTable Download Source Code Print Source Code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim weeks As New Hashtable Dim day As DictionaryEntry weeks.Add("1", "Sun") weeks.Add("2", "Mon") weeks.Add("3", "Tue") weeks.Add("4", "Wed") weeks.Add("5", "Thu") weeks.Add("6", "Fri") weeks.Add("7", "Sat") 'Display a single Item MsgBox(weeks.Item("5")) 'Search an Item If weeks.ContainsValue("Tue") Then MsgBox("Find") Else MsgBox("Not find") End If 'remove an Item weeks.Remove("3") 'Display all key value pairs For Each day In weeks MsgBox(day.Key " -- " day.Value) Next End Sub End Class

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

How to VB.Net Stack


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

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

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

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

How to VB.Net Queue


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

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

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

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

Next it check the Item "Sun" contains in the Queue.

How to VB.Net Arrays


Arrays are using for store similar data types grouping as a single unit. We can access Array elements by its numeric index. Dim week(6) As String The above Vb.Net statements means that , an Array named as week declared as a String type and it can have the capability of seven String type values. week(0) = "Sunday" week(1) = "Monday" In the above statement , we initialize the values to the String Array. week(0) = "Sunday" means , we initialize the first value of Array as "Sunday" , Dim weekName as String = week(1) We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array. In the following program , we declare an Array "week" capability of seven String values and assigns the seven values as days in a week . Next step is to retrieve the elements of the Array using a For loop. For finding the end of an Array we used the Length function of Array Object. Download Source Code Print Source Code

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

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

How to VB.Net Dyanamic Array


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

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

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

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

How to VB.Net NameValueCollection


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

Imports System.Collections.Specialized Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim markStatus As New NameValueCollection Dim key As String Dim values() As String markStatus.Add("Very High", "80") markStatus.Add("High", "60") markStatus.Add("medium", "50") markStatus.Add("Pass", "40") For Each key In markStatus.Keys values = markStatus.GetValues(key) For Each value As String In values MsgBox(key & " - " & value)

Next value Next key End Sub End Class

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

How to VB.NET String.Length()


The Length() function in String Class returned the number of characters occurred in a String. System.String.Length() As Integer Returns: Integer : The number of characters in the specified String For ex: "This is a Test".Length() returns 14. Download Source Code Print Source Code

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

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

How to VB.NET String.Insert()


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

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

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

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

How to VB.NET String.IndexOf()


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

If it does not occur as a substring, -1 is returned. Exceptions: System.ArgumentNullException: If the Argument is null. For ex: "This is a test".IndexOf("Test") returns 10 "This is a test".IndexOf("vb") returns -1 Download Source Code Print Source Code

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

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

How to VB.NET String.Format()


VB.NET String Format method replace the argument Object into a text equivalent System.Striing. System.Format(ByVal format As String, ByVal arg0 As Object) As String Parameters: String format : The format String The format String Syntax is like {indexNumber:formatCharacter} Object arg0 : The object to be formatted. Returns: String : The formatted String Exceptions:

System.ArgumentNullException : The format String is null. System.FormatException : The format item in format is invalid. The number indicating an argument to format is less than zero, or greater than or equal to the number of specified objects to format. For ex : Currency : String.Format("{0:c}", 10) will return $10.00 The currency symbol ($) displayed depends on the global locale settings. Date : String.Format("Today's date is {0:D}", DateTime.Now) You will get Today's date like : 01 January 2005 Time : String.Format("The current time is {0:T}", DateTime.Now) You will get Current Time Like : 10:10:12 Download Source Code Print Source Code

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

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

How to VB.NET String.Equals()


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

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

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

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

How to VB.NET String.CopyTo()


VB.NET String CopyTo method Copies a specified number of characters from a specified position in this instance to a specified position in an array of characters. System.String.CopyTo(ByVal sourceIndex As Integer, ByVal destination() As Char, ByVal destinationIndex As Integer, ByVal count As Integer)

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

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "CopyTo() sample" Dim chrs(5) As Char str1.CopyTo(0, chrs, 0, 6) MsgBox(chrs(0) + chrs(1) + chrs(2) + chrs(3) + chrs(4) + chrs(5)) End Sub End Class

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

How to VB.NET String.Copy()


VB.NET String Copy method is create a new String object with the same content System.String.Copy(ByVal str As String) As String Parameters: String str : The argument String for Copy method Returns:

String : Returns a new String as the same content of argument String Exceptions: System.ArgumentNullException : If the argument is null. Download Source Code Print Source Code

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

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

How to VB.NET String.Contains()


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

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

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

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

How to VB.NET String.Compare()


The VB.NET String Compare function is use to compare two String Objects. System.String.Compare(String str1,String str2, Boolean ) As Integer It returns an Integer indication lexical relationship between the two comprehends Parameters: String str1 : Parameter String String str2 : Parameter String Boolean True/False Indication to check the String with case sensitive or without case sensitive Returns: Integer : returns less than zero, zero or greater than zero. Less than zero : str1 is less than str2 zero : str1 is equal to str2 Greater than zero : str1 is grater than str2 Download Source Code Print Source Code

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

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

How to VB.NET String.Chars()


The VB.NET String Chars method return the character at the specified index of an instance System.String.Chars(ByVal index As Integer) As Char Parameters: Integer index - The character position in the returned Character. Returns: Char - The return Character. For ex : "Return test".Chars(3) return a single character 'u' If u pass a number more than String length will return an exception "Return test".Chars(25) will throw a System.IndexOutOfRangeException Exceptions: System.IndexOutOfRangeException : The index is less than zero or greater than the length of String 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 str As String = "Returned Character Chars()" Dim singleChar As Char singleChar = str.Chars(3) MsgBox(singleChar) End Sub End Class

When you run this source code you will return a messagebox show 'u'

How to VB.NET String.substring()


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

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

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

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

How to VB.NET String.Split()


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

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ") For count = 0 To strArr.Length - 1 MsgBox(strArr(count)) Next End Sub End Class

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

How to VB.NET String.EndsWith()


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

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

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

How to VB.NET String.Concat()

Concat in VB.NET String Class using for concat two specified String Object System.String.Concat(ByVal str1 As String, ByVal str2 As String) As String String Concat method returns a new String Parameters: String str1 : Parameter String String str2 : Parameter String Returns: String : A new String retrun with str1 Concat with str2 Download Source Code Print Source Code

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

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

How to VB.NET Directory operations


Using Directory class , we can create , delete , move etc. operations in VB.NET. Because of the static nature of Directory class , we do not have to instantiate the class. We can call the methods in the class directly from the Directory class. How to create a directory ? In order to create a new directory , we can call CreateDirectory directly from Directory class. Syntax : Directory.CreateDirectory(DirPath) DirPath : The name of the new directory

VB.NET : Directory.CreateDirectory("c:\testdir") How to check a directory exist or not ? Before we creating a directory , we usually check that directory exist or not. For that we are using the Exists method in the Directory class. Syntax : Directory.Exists(DirPath) as Boolean DirPath : The name of the directory Boolean : Returns true or false , if directory exist it Returns true , else it Returns false VB.NET : Directory.Exists("c:\testdir") How to move a Directory ? If we want to move a directory and its contents from one location to another , we can use the Move method in the Directory class. Syntax : Move(sourceDirName,destDirName) sourceDirName : The source directory we want to move. destDirName : The destinations directory name. VB.NET : Directory.Move("c:\testdir1\testdir2", "c:\testdir") How to delete a Directory ? When we want to delete a directory we can use the Delete method in the Directory class Syntax : Delete(DirPath) DirPath : The Directory we want to delete. VB.NET : Directory.Delete("c:\testdir1") The following VB.NET source code shows these operations : Download Source Code Print Source Code

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

If Directory.Exists("c:\testDir1") Then 'shows message if testdir1 exist MsgBox("Directory 'testDir' Exist ") Else 'create the directory testDir1 Directory.CreateDirectory("c:\testDir1") MsgBox("testDir1 created ! ") 'create the directory testDir2 Directory.CreateDirectory("c:\testDir1\testDir2") MsgBox("testDir2 created ! ") 'move the directory testDir2 as testDir in c: Directory.Move("c:\testDir1\testDir2", "c:\testDir") MsgBox("testDir2 moved ") 'delete the directory testDir1 Directory.Delete("c:\testDir1") MsgBox("testDir1 deleted ") End If End Sub End Class

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

How to VB.NET Files operations


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

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

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

VB.NET : File.Delete("c:\testDir\testFile.txt") The following VB.NET source code shows these operations : Download Source Code Print Source Code

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

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

How to VB.NET FileStream operations


The FileStream Class represents a File in the Computer. FileStream allows to move data to and from the stream as arrays of bytes. We operate File using FileMode in FileStream Class Some of FileModes as Follows : FileMode.Append : Open and append to a file , if the file does not exist , it create a new file FileMode.Create : Create a new file , if the file exist it will append to it FileMode.CreateNew : Create a new File , if the file exist , it throws exception FileMode.Open : Open an existing file How to create a file using VB.NET FileStream ? The following example shows , how to write in a file using FileStream.

Download Source Code

Print Source Code

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

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

How to VB.NET TextReader operations


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

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

End Sub End Class

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

How to VB.NET Simple TextReader


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

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

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

How to VB.NET TextWriter


Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively. The following sample source showing how write in a file using TextWriter . Download Source Code 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 writeFile As System.IO.TextWriter = New _

StreamWriter("c:\textwriter.txt") writeFile.WriteLine("vb.net-informations.com") writeFile.Flush() writeFile.Close() writeFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class

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

How to VB.NET BinaryReader


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

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

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

How to VB.NET BinaryWriter


The BinaryWriter Object works at lower level of Streams. BinaryWriter is used for write premitive types as binary values in a specific encoding stream. BinaryWriter Object works with Stream Objects that provide access to the underlying bytes. For creating a BinaryWriter Object , you have to first create a FileStream Object and then pass BinaryWriter to the constructor method . Dim writeStream As FileStream writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) The main advantages of Binary information is that it is not easily human readable and stores files as Binary format is the best practice of space utilization. Download Source Code Print Source Code

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

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

Search Tables in a Dataset Sql Server


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The Dataset may comprise data for one or more members, corresponding to the number of rows. The SqlDataAdapter object allows us to populate DataTables in a DataSet.

In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset. Download Source Code Print Source Code

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

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"

Dataset table row count in SQL Server


The DataSet contains copy of the data we requested through the SQL statement. The DataSet consists of DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data set may comprise data for one or more

members, corresponding to the number of rows. The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet 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() 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"

How to find column definition - Sql Server


Dataset represents a collection of data retrieved from the Data Source. The Dataset can work with the data it contains, without knowing the source of the data coming from. The SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset. The Dataset can contains more than one Table at a time. The data inside Table is in the form of Rows and Columns .

In some situations we have to find the column headers in a DataTable. There is a ColumnsCollection object in the Datatable hold the column Definitions. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim column As DataColumn Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() dt = ds.Tables(0) For Each column In dt.Columns MsgBox(column.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"

How to create DataSet without Databse


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

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

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

How to multiple tables in Dataset - Sql Server


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The SqlDataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset.

We can populate Dataset with more than one table at a time using SqlDataAdapter Object . The following VB.NET source code shows how to a single SqlDataAdapter fill Dataset with multiple tables. Download Source Code Print Source Code

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

--

" &

--

" &

End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"

How to add relations between tables in a Dataset


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

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table1") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table2") adapter.Dispose() command.Dispose() connection.Close() 'creating data relations Dim relation As DataRelation Dim table1Column As DataColumn Dim table2Column As DataColumn 'retrieve column table1Column = ds.Tables("Table1").Columns(0)

table2Column = ds.Tables("table2").Columns(0) 'relating tables relation = New DataRelation("relation", table1Column, table2Column) 'assign relation to dataset ds.Relations.Add(relation) MsgBox("Data relation completed") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here"

How to merge tables in a Dataset - Sql Server


The DataSet contains copy of the data we requested through the SQL statement. The SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using SqlDataAdapter Object. The DataTableCollection contains zero or more DataTable objects. In some situation we want to combine the result of multiple SQL query as a single result set. In that case we can use the Dataset's Merge method for doing this. The tables involved in the merge should be identical, that is the columns are similar data types . Download Source Code Print Source Code

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

connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table(0)") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table(1)") adapter.Dispose() command.Dispose() connection.Close() ds.Tables(0).Merge(ds.Tables(1)) dt = ds.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " -Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class " & dt.Rows(i).Item(1))

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here"

Dataadapter with dataset - sql sever


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

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

Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter = New SqlDataAdapter("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter SelectCommand - Sql Server


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

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

MsgBox(ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter InsertCommand - Sql Server


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

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

Dataadapter UpdateCommand - Sql Server

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

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

Dataadapter DeleteCommand - Sql Server


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

Print Source Code

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

Dataadapter with DataGridView - Sql Server


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

Print Source Code

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

How to create a DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search in a DataTable , additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured both design time and run time . Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing the DataTable. We can create DataView in two different ways. We can use the DataView constructor, or you can create a reference to the DefaultView property of the DataTable. The DataView constructor can be empty, or it can take either a DataTable as a single argument, or a DataTable along with filter criteria, sort criteria, and a row state filter. dataView = dataSet.Tables(0).DefaultView The following source code shows how to create a DataView in VB.NET. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.

Download Source Code

Print Source Code

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

How to sort DataView


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

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

How to add new rows in DataView


The DataView provides different views of the data stored in a DataTable. DataViews can be created and configured at both design time and run time . We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable. We can add new rows in the DataView using AddNew method in the DataView. The following source code shows how to add new row in a DataView . Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event. Download Source Code
Imports System.Data.SqlClient

Print Source Code

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

How to Find a row in DataView


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

Dim index As Integer = DataView.Find("Product5") Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand 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, "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() & " ("Product_Name").ToString()) End If Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

" & dv(index)

How to update rows in DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search a DataTable , additionally we can add new rows and modify the content in a DataTable. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. Also we can create multiple DataViews for any given DataTable.

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

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Update") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_Name", DataViewRowState.CurrentRows) Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Product not found") Else dv(index)("Product_Name") = "Product11" MsgBox("Product Updated !") End If DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to delete rows in DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the

content in a DataTable. Also we can delete the data from the DataView . The following source code shows how to delete the data from DataView. Download Source Code Print Source Code

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

How to create a new DataTable from DataView


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

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand 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, "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

VB.NET DataGridView binding - Sql Server


You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain. The following vb.net program shows how to bind a SQL Server dataset in a DataGridView. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class

DataGridView Sorting/Filtering in VB.NET


The DataGridView control provides a customizable table for displaying data. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. A DataView provides a means to filter and sort data within a DataTable. The following vb.net program shows how to filter and sort a DataGridView by using a DataView Object. Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Titles" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Titles_table") connection.Close() Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv End Sub

End Class

DataGridView adding rows and columns in VB.NET


The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms. The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The DataGridView control is used to display data from a variety of external data sources. Alternatively, you can add rows and columns to the control and manually populate it with data. The following vb.net source code shows how to manually create Columns and Rows in a DataGridView. DataGridView1.Columns(Index).Name = "Column Name" Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) End Sub End Class

DataGridView hiding rows and columns in VB.NET


The DataGridView control provides a customizable table for displaying data. It gives you number of properties, methods and events to customize its appearance and behavior. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete solution for displaying tabular data with Windows Forms . The following vb.net source code manually creates a DataGridView columns and rows and hide the second column and second row. DataGridView1.Rows(Index).Visible = False DataGridView1.Columns(Index).Visible = False Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).Visible = False End Sub End Class

Adding Button to DataGridView in VB.NET


The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. With the DataGridViewButtonColumn, you can display a column of cells that contain buttons.You can respond to user clicks in button cells by handling the DataGridView.CellClick event. The following vb.net program shows how to add a Button in Cell of a DataGridView control. Also it showing in the DataGridView.CellClick event which button the user clicked. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"}

DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim btn As New DataGridViewButtonColumn() DataGridView1.Columns.Add(btn) btn.HeaderText = "Click Data" btn.Text = "Click Here" btn.Name = "btn" btn.UseColumnTextForButtonValue = True End Sub Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick If e.ColumnIndex = 3 Then MsgBox(("Row : " + e.RowIndex.ToString & " Col : ") + e.ColumnIndex.ToString) End If End Sub End Class

Adding CheckBox to DataGridView in VB.NET


The DataGridView control uses several column types to display its information and enable users to modify or add information. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. The following vb.net program shows how to add a CheckBox in Cell of a DataGridView control and set the third row checkbox value as true. If you want to respond immediately when users click a check box cell, you can handle the CellClick event, but this event occurs before the cell value is updated. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"}

DataGridView1.Rows.Add(row) Dim chk As New DataGridViewCheckBoxColumn() DataGridView1.Columns.Add(chk) chk.HeaderText = "Check Data" chk.Name = "chk" DataGridView1.Rows(2).Cells(3).Value = True End Sub End Class

Adding ComboBox to DataGridView in VB.NET


The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. You can populate the drop down list used for all cells the same way you would populate a ComboBox drop down list, either manually through the collection returned by the Items property, or by binding it to a data source through the DataSource, DisplayMember, and ValueMember properties. The following vb.net program shows how to add a ComboBox in Cell of a DataGridView control. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim cmb As New DataGridViewComboBoxColumn() cmb.HeaderText = "Select Data" cmb.Name = "cmb" cmb.MaxDropDownItems = 4 cmb.Items.Add("True") cmb.Items.Add("False") DataGridView1.Columns.Add(cmb) End Sub End Class

Adding Image to DataGridView in VB.NET


The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data. We can add an Image control in a column of DataGridView. This column type exposes Image and ImageLayout properties in addition to the usual base class properties. Setting the columns Image property results in that image being displayed by default for all the cells in that column. Populating an image column manually is useful when you want to provide the functionality of a DataGridViewButtonColumn, but with a customized appearance. The following vb.net program shows how to add a Image in column of a DataGridView control. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim img As New DataGridViewImageColumn() Dim inImg As Image = Image.FromFile("Image Path") img.Image = inImg DataGridView1.Columns.Add(img) img.HeaderText = "Image" img.Name = "img" End Sub End Class

Adding ViewLink to DataGridView in VB.NET


The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. We can add hyperlink in the column of a DataGridView , the column type contains cells of type DataGridViewLinkCell and renders the text in the cell to look like a hyperlink. Link columns are not generated automatically when data binding a DataGridView control. To use link columns, you must create them manually and add them to the collection returned by the Columns property.

The following vb.net program shows how to add a hyperlink in a column of DataGridView control. Download Source Code Print Source Code

Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim lnk As New DataGridViewLinkColumn() DataGridView1.Columns.Add(lnk) lnk.HeaderText = "Link Data" lnk.Name = "http://vb.net-informations.com" lnk.Text = "http://vb.net-informations.com" lnk.UseColumnTextForLinkValue = True End Sub End Class

How to Paging in DataGridView

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

Print Source Code

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

Just In Time Compiler


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

.Net Framework Class Library (FCL)


The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture . The .Net Framework Class Library (FCL) includes a huge collection of reusable classes , interfaces, and value types that expedite and optimize the development process and provide access to system functionality. The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of

identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.

How to Common Language Runtime


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

Common Language Runtime


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

.Net Metadata
Metadata in .Net is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module. During the compile time Metadata 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. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.

.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).

What is .Net Strong Name


Strong name consists of an Assemblys identity, that means the Assemblies can be assigned a cryptographic signature. The strong name guarantees the integrity of the assembly which prevents someone from taking over the name of the assembly. Strong Name includes the name of the .net assembly, version number, culture identity, and a public key token. It is generated from an assembly file using the corresponding private key. Strong names guarantee name uniqueness by relying on unique key pairs.

To create a key pair At the command prompt, type the following command: sn -k fileName
In this command, file name is the name of the output file containing the key pair.

.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification. The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes.
These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.

.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.

Microsoft Intermediate Language


MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). During the compile time , the compiler convert the source code into Microsoft Intermediate Language (MSIL) .Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native code. 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. When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata. The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations

Common Type System


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

Common Language Specification


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

Code Access Security


The .NET Security Model provides code access permissions and code identity permissions. Code Access Security is the part of the .NET security model that determines whether or not the code is

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

Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap. The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.

How to read a URL Content


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

Download Source Code

Print Source Code

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

How to send email from VB.NET


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

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

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

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

How to use IF ELSE in VB.NET


The conditional statement IF ELSE , is use for examining the conditions that we provided, and making decision based on that contition. The conditional statement examining the data using comparison operators as well as logical operators.
If [your condition here] Your code here Else Your code Here End If

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

Else End If

Your code Here

Just take a real-time example - When we want to analyze a mark lists we have to apply some conditions for grading students depends on the marks. Following are the garding rule of the mark list: 1) If the marks is greater than 80 then the student get higher first class 2) If the marks less than 80 and greater than 60 then the student get first class 3) If the marks less than 60 and greater than 40 then the student get second class 4) The last condition is , if the marks less than 40 then the student fail. Now here implementing these conditions in a VB.NET program.
1. 2. 3. 4. 5. 6. 7. 8. 9. If totalMarks >= 80 Then MsgBox("Got Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Got First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If

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

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

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

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

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

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

How to use FOR NEXT loop in vb.net


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

var : The counter for the loop to repeat the steps. starValue : The starting value assign to counter variable . endValue : When the counter variable reach end value the Loop will stop . loopBody : The source code between loop body Lets take a simple real time example , If you want to show a messagebox 5 times and each time you want to see how many times the message box shows.
1. 2. 3. 4. 5. startVal=1 endVal = 5 For var = startVal To endVal show message Next var

Line 1: Loop starts value from 1 Line 2: Loop will end when it reach 5 Line 3: Assign the starting value to var and inform to stop when the var reach endVal Line 4: Execute the loop body

Line 5: Taking next step , if the counter not reach the endVal VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " & var & " Times ") Next var End Sub End Class

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

Download Source Code

Print Source Code

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

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

Custom Exceptions in VB.NET


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

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

Print Source Code

Public Class MyCustomException Inherits System.ApplicationException Public Sub New(ByVal message As String) MyBase.New(message) MsgBox(message) End Sub End Class

How to use FOR EACH loop in VB.NET


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

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

Line 1: Assigning the site name in a variable Line 2: This line is extracting the single item from the group

Line 3: Loop body Line 4: Taking the next step Download Source Code Print Source Code

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

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

How to use vb.net While End While loop


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

Condition : The condition set by the user


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

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

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

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

How to find IP Address of Host


Syste.net namespace provide the infomation about IP Address .

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

Print Source Code

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

Net Remoting Architecture


The .NET Remoting provides an inter-process communication between Application Domains by using Remoting Framework. The applications can be located on the same computer, different computers on the same network, or on computers across separate networks. The .NET Remoting supports distributed object communications over the TCP and HTTP channels by using Binary or SOAP formatters of the data stream. The main three components of a Remoting Framework are : 1. Remotable Object. 2. Remote Listener Application - (listening requests for Remote Object) 3. Remote Client Application - (makes requests for Remote Object) The Remote Object is implemented in a class that derives from System.MarshalByRefObject .

You can see the basic workflow of .Net Remoting from the above figure. When a client calls the Remote method, the client does not call the methods directly . It receives a proxy to the remote object and is used to invoke the method on the Remote Object. Once the proxy receives the method

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

VB.NET Remoting Apllication


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

Remote Client Application Remote Configuration

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

Print Source Code

Copy and paste the above VB.Net source code into a file and save it as RemoteTime.vb Compile the class RemoteTime.vb into a library using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /t:library RemoteTime.vb After you compile the RemoteTime.vb , you will get a file called RemoteTime.dll in the directory which you saved the source file.

Remote Listener Application


We already created a Remote Type Object RemoteTime in the previous section. We have to create a listener Object for enable Objects in other application domains to create instances of this object (RemoteTime) Remotely. When creating a listener Object we have to choose and register a channel

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

Print Source Code

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

Click here to download TimeListener.exe.config . Compile the class file TimeListener.vb using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command:

vbc /r:RemoteTime.dll TimeListener.vb After you compile the TimeListener.vb , you will get a file called TimeListener.exe in the directory which you saved the source file

Remote Client Application


The Client application for calling Remote Object's method in VB.Net is pretty simple and straight forward. The .NET Remoting system will intercept the client calls, forward them to the remote object, and return the results to the client. The Client Application have to register for the Remote Type also. Here in the Client application in VB.Net , creating an instance of the Remote Type, RemoteTime Object , and call the method getTime() . Aditionally it uses the configuration file Client.exe.config for the communication information for the Remoting Framework. Download Source Code
Imports System Imports System.Runtime.Remoting Public Class Client Public Shared Sub Main() RemotingConfiguration.Configure("Client.exe.config") Dim remoteTimeObject As New RemoteTime() Console.WriteLine(remoteTimeObject.getTime()) End Sub End Class

Print Source Code

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

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

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

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

Click here to download Client.exe.config .

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 = ""

Print Source Code

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.

Compiling and Running Remote Application


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

Compile these VB.Net class files using the command-line tools that ship with the .NET Framework SDK. vbc /t:library RemoteTime.vb vbc /r:RemoteTime.dll TimeListener.vb vbc /r:RemoteTime.dll Client.vb Note: You have to provide the physical path of each source files when you compile the source code , for example : if the source code files are in the folder c:\SRC , you have to give path like vbc /r:c:\SRC\RemoteTime.dll c:\SRC\TimeListener.vb After you complied the VB.Net source code files, you will get additional three files in the SRC folder. They are : RemoteTime.dll TimeListener.exe Client.exe To run the application Create two new folders and give the name like Server and Client respectively. Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the Server folder. Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder. Open a command prompt on Server folder and type TimeListener Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..." Open a command prompt on Client folder and type Client. Then you will get the current time from remote Object. Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more on Remoting ...

Remote Client Application


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

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

Print Source Code

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

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

After you compile the Client.vb , you will get a file called Client.exe in the directory which you saved the source file

Remote Listener Application


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

Print Source Code

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

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

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.

How to create an XML file in VB.NET


XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). If we create an XML file in one platform it can be used in other platforms also. For creating a new XML file in VB.NET, we are using XmlTextWriter class . The class takes FileName and Encoding as argument. Also we are here passing formating details . The following source code creating an XML file product.xml and add four rows in the file. Download Source Code Print Source Code

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

Output of the above source code :

How to XML in VB.NET


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

Sample XML File

The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . These classes are stored in the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal storage format. You can use any text editor to create an XML file . More over XML files are readable by humans as well as computers. From the following links you can see how to use XML in VB.NET.

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


XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the information embedded in XML tags in an XML file. In the previous program we create an XML file and named it as products.xml. The following program read that file and extract the contents inside the XML tag. We can read an XML file in several ways depends on our requirement. This program read the content in Node wise . Here we are using XmlDataDocument class to read the XML file . In this program it search the Node < Product > and its child Nodes and extract the data in child nodes. Download Source Code Print Source Code

Imports System.Xml Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

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

Click here to download the input file product.xml

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


XML is a tag based language, that means the document is made up of XML tags that contain information. We can create an XML file in several ways. In the previous section we create an XML file using XmlTextWriter Class. Here we are creating an XML file Product.XML using an ADO.NET Dataset. For that we have to manually create a Datatable first and add the data of Product.XML in the Datatable . Then add the Datatable in a Dataset . Call the method WriteXml of Dataset and pass the file name Product.XML as argument. Download Source Code
Imports System.Xml 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)

Print Source Code

fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" ds.WriteXml("Product.xml") MsgBox("Done") End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class

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


XML is a platform independent language, so the information formatted in XML can be use in any other platforms (Operating Systems) . The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . In the previous section we already saw how to read an XML file through Node navigation . Here we are going to read an XML file using an DataSet. Here Dataset is using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. Click here to download the input file product.xml Download Source Code Print Source Code

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

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


XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format. There are several ways to create an XML file . In the previous sections we already saw how to create an XML file using XmlTextWriter and also created an XML file using manually created Dataset. Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as argument. Download Source Code Print Source Code

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

How to search in an XML file


XML files are made up of tags that contains information. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format. The following source code shows how to search an item in an XML file using Dataset . Here Dataset using an XmlReader for read the content of the file. Locate the XML file using XmlReader

and pass the XmlReader as argument of Dataset. By using the Dataset , search the product Product2 in the file Product.XML with the help of DataView. Download Source Code Print Source Code

Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product2") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_Name").ToString() & " ("Product_Price").ToString()) End If End Sub

" & dv(index)

Click here to download the input file product.xml

How to filter data in an XML file


XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). If we create an XML file in one platform it can be used in other platforms also. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format. Here we are going to filter an XML file content and store the result in a newly created XML file. We have an XML file Product.XML , and it has a field Product_Price. We are giving a search criteria like the Product_Price >= 3000 and store the result in a newly created XML file Result.XML. Download Source Code Print Source Code

Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader

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

Click here to download the input file product.xml

How to insert data from xml to database


XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format. Here we are going to insert the values of an XML file to a Database Table using SQL insert command. Here the Dataset using an XmlReader for read the content of the XML file Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. Also establish a connection to the Database using a connectionstring . After getting the data from XML file to the Dataset , we can loop through the dataset values and use insert command to add the values to the Product table in the Databse. Download Source Code Print Source Code

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 command As SqlCommand Dim adpter As New SqlDataAdapter Dim ds As New DataSet Dim xmlFile As XmlReader Dim sql As String Dim product_ID As Integer Dim Product_Name As String Dim product_Price As Double connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString)

xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile) Dim i As Integer connection.Open() For i = 0 To ds.Tables(0).Rows.Count - 1 product_ID = Convert.ToInt32(ds.Tables(0).Rows(i).Item(0)) Product_Name = ds.Tables(0).Rows(i).Item(1) product_Price = Convert.ToDouble(ds.Tables(0).Rows(i).Item(2)) sql = "insert into Product values(" & product_ID & ",'" & Product_Name & "'," & product_Price & ")" command = New SqlCommand(sql, connection) adpter.InsertCommand = command adpter.InsertCommand.ExecuteNonQuery() Next connection.Close() End Sub End Class

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

How to xml to DataGridView


XML is a platform independent language, so the information formatted in XML file can be use in any other platforms . The .Net technology is widely supported XML file format. The following source code shows , how to load data in a DataGridView from an XML file . Here the Dataset using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. When the Dataset retrieves the data, it passes as DataSource to DataGridView . Download Source Code Print Source Code

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

Click here to download the input file product.xml

How to serialization in xml

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

How to serialize a .Net Object to XML


Serialization of XML to common language runtime objects enables one to convert XML documents into a form where they are easier to process using conventional programming languages. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . The following program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer class for serialize the Dataset Object. Download Source Code Print Source Code

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

dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class

Click here to download serialXML.xml

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


XML is a general purpose tag based language and very easy to transfer and store data across applications. XML Serialization is the process of serializing a .Net Object to the form of XML file or from an XML to .Net Object. During XML serialization, only the public properties and fields of an object are serialized. The following source code shows how to de-serialize the DataSet as it is streamed from an XML file back into memory. Download Source Code Print Source Code

Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class

Click here to download serialXML.xml

How to serialize a .Net Object to XML


Serialization of XML to common language runtime objects enables one to convert XML documents into a form where they are easier to process using conventional programming languages. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . The following program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer class for serialize the Dataset Object.

Download Source Code

Print Source Code

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

Click here to download serialXML.xml

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


XML is a general purpose tag based language and very easy to transfer and store data across applications. XML Serialization is the process of serializing a .Net Object to the form of XML file or from an XML to .Net Object. During XML serialization, only the public properties and fields of an object are serialized. The following source code shows how to de-serialize the DataSet as it is streamed from an XML file back into memory.

Download Source Code

Print Source Code

Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class

Click here to download serialXML.xml

Vous aimerez peut-être aussi