You are on page 1of 79

y

ADO.NET Data Providers Tutorial

ADO.NET Connection Object


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

ADO.NET SQL Server Connection


The SqlConnection Object is Handling the part of physical communication between the application and the SQL Server Database. An instance of the SqlConnection class in .NET Framework is supported the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the database resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the SQL Server Database. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class You have to provide the necessary informations to the Connection String. connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" From the above statement replace ServerName, DatabaseName, UserName, Password to the actual names.

OleDbConnection

ADO.NET OLEDB Connection

An instance of the OleDbConnection class in .NET Framework is supported the OLEDB Data Provider. The OleDbConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the Database connected by the OLEDB Data Provider. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdatabasename.mdb;" cnn = New OleDbConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class You have to provide the necessary informations to the Connection String. connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = yourdatabasename.mdb;" From the above statement replace yourdatabasename.mdb to the actual names.

OdbcConnection

ADO.NET ODBC Connection


An instance of the OdbcConnection class in .NET Framework is supported the ODBC Data Provider. The OdbcConnection instance takes Connection String as argument and pass the value to the Constructor statement. When the connection is established , SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the database. Once the Database activities over , Connection should be closed and release the resources . The Close() method in SqlConnection class is used to close the Database Connection. The Close method rolls back any pending transactions and releases the Connection from the Database connected by the ODBC Data Provider. Download Source Code Imports System.Data.Odbc Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OdbcConnection connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;" cnn = New OdbcConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ")

cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class You have to provide the necessary informations to the Connection String. connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ = yourdatabasename.mdb;" From the above statement replace yourdatabasename.mdb to the actual names.

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

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

ADO.NET ExecuteNonQuery in SqlCommand Object


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

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

ADO.NET ExecuteNonQuery in OleDbCommand Object


ExecuteNonQuery() is one of the most frequently used method in OleDbCommand Object and is used for executing statements that do not return result set. ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update and Delete perform by ExecuteNonQuery(). The following example shows how to use the method ExecuteNonQuery() through OleDbCommand Object. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close()

MsgBox(" ExecuteNonQuery in OleDbConnection executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your realtime variables.

ADO.NET ExecuteNonQuery in OleDbCommand Object


ExecuteNonQuery() is one of the most frequently used method in OleDbCommand Object and is used for executing statements that do not return result set. ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update and Delete perform by ExecuteNonQuery(). The following example shows how to use the method ExecuteNonQuery() through OleDbCommand Object. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close() MsgBox(" ExecuteNonQuery in OleDbConnection executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your realtime variables.

ADO.NET ExecuteScalar in OleDbCommand Object


ExecuteScalar() in OleDbCommand Object is used for get a single value from Database after its execution. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set. If the Result Set contains more than one columns or rows , it takes only the first column of first row, all other values will ignore. If the Result Set is empty it will return a Null

reference. It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose() cnn.Close() MsgBox(" No of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" You have to replace the string with your realtime variables.

ADO.NET ExecuteReader in SqlCommand Object


ExecuteReader() in SqlCommand Object send the SQL statements to Connection Object and populate a SqlDataReader Object based on the SQL statement. When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The SqlDataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object. Download Source Code Print Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String Dim reader As SqlDataReader

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " 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" You have to replace the string with your realtime variables.

ADO.NET ExecuteReader in OleDbCommand Object


ExecuteReader() in OleDbCommand Object send the SQL statements to Connection Object and populate a OleDbDataReader Object based on the SQL statement. When the ExecuteReader method in OleDbCommand Object execute , it instantiate a OleDb.OleDbDataReader Object. The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The OleDbDataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object. Download Source Code Print Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As OleDbConnection Dim cmd As OleDbCommand Dim sql As String Dim reader As OleDbDataReader connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " 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 = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.

How to ADO.NET DataReader


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

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

How to ADO.NET SqlDataReader


SqlDataReader Object provides a connection oriented data access to the SQL Server data Sources. ExecuteReader() in the SqlCommand Object send the SQL statements to SqlConnection Object and populate a SqlDataReader Object based on the SQL statement. Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()

When the ExecuteReader method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object. When started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . SqlDataReader.Read() Download Source Code Print Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " 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" You have to replace the string with your realtime variables.

How to ADO.NET OleDbDataReader


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

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

" &

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 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" You have to replace the string with your realtime variables.

Schema Informations from SqlDataReader


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

Schema Informations from OleDbDataReader


The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. When the ExecuteReader method in oledbCmd Object execute , it instantiate a OleDb.OleDbDataReader Object. Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() While a OleDbDataReader is open, you can retrieve schema information about the current result set using the GetSchemaTable method. GetSchemaTable returns a DataTable object populated with rows and columns that contain the schema information for the current result set. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim oledbCnn As OleDbConnection Dim oledbCmd As OleDbCommand Dim sql As String

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" oledbCnn = New OleDbConnection(connetionString) Try oledbCnn.Open() oledbCmd = New OleDbCommand(sql, oledbCnn) Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader() Dim schemaTable As DataTable = oledbReader.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.Rows For Each column In schemaTable.Columns MsgBox(String.Format("{0} = {1}", column.ColumnName, row(column))) Next Next oledbReader.Close() oledbCmd.Dispose() oledbCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.

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

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

What is SqlDataAdapter

SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset Object. Dim adapter As New SqlDataAdapter The SqlDataAdapter Object and DataSet objects are combine to perform both data access and data manipulation operations in the SQL Server Database. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the SqlDataAdapter. Download Source Code 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" You have to replace the string with your realtime variables.

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

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

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

VB.NET ADO.NET Dataset Tutorial


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

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

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

How to Dataset with Sql Server

The DataSet contains the copy of the data we requested through the SQL statement. We can use Dataset in combination with SqlDataAdapter class . The SqlDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) adapter.Dispose() command.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " ds.Tables(0).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" You have to replace the string with your real time variables. -" &

How to Dataset with OLEDB Data Source


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

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

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

Search Tables in a Dataset Sql Server


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The Dataset may comprise data for one or more members, corresponding to the number of rows. The SqlDataAdapter object allows us to populate DataTables in a DataSet. In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim tables As DataTable Dim i As Integer Dim sql As String

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() For Each tables In ds.Tables MsgBox(tables.TableName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

Search Tables in a Dataset OLEDB Data Source


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data inside Table is in the form of Rows and Columns . The OleDbDataAdapter object allows us to populate DataTables in a DataSet. In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table")

oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables.Count - 1 MsgBox(ds.Tables(i).TableName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

Dataset table row count in SQL Server

The DataSet contains copy of the data we requested through the SQL statement. The DataSet consists of DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data set may comprise data for one or more members, corresponding to the number of rows. The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset. Download Source Code 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" You have to replace the string with your real time variables.

Dataset table row count - OLEDB Data Source


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

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to find column definition - Sql Server

Dataset represents a collection of data retrieved from the Data Source. The Dataset can work with the data it contains, without knowing the source of the data coming from. The SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use

Fill method in the SqlDataAdapter for populating data in a Dataset. The Dataset can contains more than one Table at a time. The data inside Table is in the form of Rows and Columns . In some situations we have to find the column headers in a DataTable. There is a ColumnsCollection object in the Datatable hold the column Definitions. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim column As DataColumn Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() dt = ds.Tables(0) For Each column In dt.Columns MsgBox(column.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to find column definition - OLEDB Data Source


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

Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim sql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbAdapter.Fill(ds, "OLEDB Temp Table") oledbAdapter.Dispose() connection.Close() dt = ds.Tables(0) For i = 0 To dt.Columns.Count - 1 MsgBox(dt.Columns(i).ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" You have to replace the string with your real time variables.

How to create DataSet without Databse


Dataset represents a collection of data retrieved from the Data Source. The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The data set may comprise data for one or more members, corresponding to the number of rows. We can fill the data in Dataset without calling SQL statements. For that we manually create a DataTable and add data in it. Download Source Code 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 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" You have to replace the string with your real time variables.

--

" &

--

" &

How to multiple tables in Dataset - OLEDB Data Source


The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The OleDbDataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using OleDbDataAdapter Object . The following VB.NET source code shows how to a single OleDbDataAdapter fill Dataset with multiple tables. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(firstSql, connection) oledbAdapter.Fill(ds, "First Table")

oledbAdapter.SelectCommand.CommandText = secondSql oledbAdapter.Fill(ds, "Second Table") oledbAdapter.Dispose() connection.Close() 'retrieve first table data For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " & ds.Tables(0).Rows(i).Item(1)) Next 'retrieve second table data For i = 0 To ds.Tables(1).Rows.Count - 1 MsgBox(ds.Tables(1).Rows(i).Item(0) & " -- " & ds.Tables(1).Rows(i).Item(1)) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.

How to add relations between tables in a Dataset


The DataSet contains DataTableCollection and their DataRelationCollection. The DataSet.Relations property is an instance of the DataRelationsCollection Object. We can create parent child data relations between DataTable using Datarelation Object. We can relate one or more column from different tables using DataRelation Object . The columns involved in the DataRelation should be identical data types. That is the parent and child column should be similar Data Types. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table1") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table2") adapter.Dispose()

command.Dispose() connection.Close() 'creating data relations Dim relation As DataRelation Dim table1Column As DataColumn Dim table2Column As DataColumn 'retrieve column table1Column = ds.Tables("Table1").Columns(0) table2Column = ds.Tables("table2").Columns(0) 'relating tables relation = New DataRelation("relation", table1Column, table2Column) 'assign relation to dataset ds.Relations.Add(relation) MsgBox("Data relation completed") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables.

How to merge tables in a Dataset - Sql Server

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

How to merge tables in a Dataset - OLEDB Data Source


The DataSet contains copy of the data we requested through the SQL statement. The OleDbDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in the OleDbDataAdapter for populating data in a Dataset. We can populate Dataset with more than one table at a time using OleDbDataAdapter Object. The DataTableCollection contains zero or more DataTable objects. In some situation we want to combine the result of multiple SQL query results as a single result set. In that case we can use the Dataset's Merge method for doing this. The tables involved in the merge should be identical. The following VB.NET source code shows how to merge the tables from two different dataset. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds1 As New DataSet Dim ds2 As New DataSet Dim dt As DataTable Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter(firstSql, connection) oledbAdapter.Fill(ds1, "First Table")

oledbAdapter.SelectCommand.CommandText = secondSql oledbAdapter.Fill(ds2, "Second Table") oledbAdapter.Dispose() connection.Close() ds1.Tables(0).Merge(ds2.Tables(0)) dt = ds1.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " Next -" & dt.Rows(i).Item(1))

Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" You have to replace the string with your real time variables. y

ADO.NET DataAdapter and Dataset


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

End Try End Sub End Class

Dataadapter with dataset - OLEDB Data Source


OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object . The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects. The OleDbDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill method of the OleDbDataAdapter for populating data in a Dataset. The following source code shows a simple program that uses OleDbDataAdapter to retrieve data from Data Source with the help of OleDbConnection object and populate the data in a Dataset. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Try connection.Open() oledbAdapter = New OleDbDataAdapter("Your SQL Statement Here") oledbAdapter.Fill(ds) oledbAdapter.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter SelectCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism. The SelectCommand property of the SqlDataAdapter is a Command object that retrieves data from the data source. The following program shows the SqlDataAdapter using its SelectCommand property to retrieve the data from the Data Source. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection

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

Dataadapter SelectCommand - OLEDB Data Source


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

Dataadapter InsertCommand - Sql Server

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

Dataadapter InsertCommand - OLEDB Data Source


OleDbDataAdapter provides the communication between the Dataset and the Data Source with the help of OleDbConnection Object . The InsertCommand in OleDbDataAdapter Object manages to insert the data in the specified Data Source . In the following Source Code shows how to insert data in the Data Source using OleDbDataAdapter and OleDbCommand object. Open a connection to the Data Source with the help of OleDbConnection object and create an OleDbCommand object with insert SQL statement, and assign the OleDbCommand to the SqlDataAdapter's InsertCommand. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "insert into user values('user1','password1')" Try connection.Open() oledbAdapter.InsertCommand = New OleDbCommand(sql, connection) oledbAdapter.InsertCommand.ExecuteNonQuery() MsgBox("Row(s) Inserted !! ")

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

Dataadapter UpdateCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications, that are run on a DataSet object. The following code samples that demonstrate how to use the SqlDataAdapter object to update a SQL Server database using UpdateCommand properties in SqlDataAdapter. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "update product set product_price = 1001 where Product_name ='Product7'" Try connection.Open() adapter.UpdateCommand = connection.CreateCommand adapter.UpdateCommand.CommandText = sql adapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter UpdateCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the Data Source with the data modifications that are run on a DataSet object. The following code samples that demonstrate how to use the OleDbDataAdapter object to update an OLEDB Data Source using UpdateCommand properties in OleDbDataAdapter. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As New OleDbDataAdapter Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"

connection = New OleDbConnection(connetionString) sql = "update Users set Password = 'new password' where UserID = 'user1'" Try connection.Open() oledbAdapter.UpdateCommand = connection.CreateCommand oledbAdapter.UpdateCommand.CommandText = sql oledbAdapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row(s) Updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter DeleteCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications, that are run on a DataSet object. The following code samples that demonstrate how to use the SqlDataAdapter object to update a SQL Server database using UpdateCommand properties in SqlDataAdapter. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "delete product where Product_name ='Product7'" Try connection.Open() adapter.DeleteCommand = connection.CreateCommand adapter.DeleteCommand.CommandText = sql adapter.DeleteCommand.ExecuteNonQuery() MsgBox("Row(s) deleted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter DeleteCommand - OLEDB Data Source


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

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

Dataadapter with CommandBuilder - Sql Server


The DataAdapter is a part of the ADO.NET Data Provider. ADO.NET DataAdapter is used to manage four separate Command objects. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object. The SqlCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the SqlCommandBuilder object. The SqlCommandBuilder opens the Connection associated with the DataAdapter and makes a round trip to the server each and every time it's asked to construct the action queries. It closes the Connection when it's done. The following Source Code demonstrate how to use the SqlDataAdapter object to update a SQL Server database with data modifications that are run on a DataSet object that is populated with data from a table in the database using SqlCommandBuilder object. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim cmdBuilder As SqlCommandBuilder Dim ds As New DataSet Dim sql As String Dim i As Int32 connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(sql, connection) cmdBuilder = New SqlCommandBuilder(adapter) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 ds.Tables(0).Rows(i).Item(2) = ds.Tables(0).Rows(i).Item(2) + 100 Next adapter.Update(ds.Tables(0)) connection.Close() MsgBox("Data updated ! ")

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

Dataadapter with CommandBuilder - OLEDB


The OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter is used to manage four separate Command objects. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object. The OleDbCommand objects that are assigned to these properties can be created manually in code or automatically generated by using the OleDbCommandBuilder object. The OleDbCommandBuilder opens the Connection associated with the OleDbDataAdapter and makes a round trip to the server each and every time it's asked to construct the action queries. It closes the Connection when it's done. The following Source Code demonstrate how to use the OleDbDataAdapter object to update a OLEDB Data Source with data modifications that are run on a DataSet object that is populated with data from a table in the database using OleDbCommandBuilder object. Download Source Code Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim oledbCmdBuilder As OleDbCommandBuilder Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) sql = "select * from tblUsers" Try connection.Open() oledbAdapter = New OleDbDataAdapter(sql, connection) oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) oledbAdapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 ds.Tables(0).Rows(i).Item(2) = "neweamil@email.com" Next oledbAdapter.Update(ds.Tables(0)) connection.Close() MsgBox("Email address updates !") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with DataGridView - Sql Server


SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Sourcewhere the data coming from. So the SqlDataAdapter manage the communication between these two Objects. The TableMapping Collections help the SqlDataAdapter to do this task. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSet object. The following source code demonstrate how to update a Dataset through

SqlDataAdapter using a DataGridView. For running this source code , open a new VB.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code. Download Source Code Imports System.Data.SqlClient Public Class Form1 Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim cmdBuilder As SqlCommandBuilder 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 System.EventArgs) Handles Button1.Click connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(Sql, connection) adapter.Fill(ds) connection.Close() DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try cmdBuilder = New SqlCommandBuilder(adapter) changes = ds.GetChanges() If changes IsNot Nothing Then adapter.Update(changes) End If MsgBox("Changes Done") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Dataadapter with DataGridView - OLEDB


OleDbDataAdapter provides the communication between the Dataset and the OLEDB Data Source with the help of OleDbConnection Object . The OleDbConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from. So the OleDbDataAdapter manage the communication between these two Objects. The TableMapping Collection help the OleDbDataAdapter to do this task. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update the database with the data modifications that are run on a DataSet object. The following source code demonstrate how to update a Dataset through OleDbDataAdapter using a DataGridView. For running this source code , open a new VB.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code. Download Source Code

Imports System.Data.OleDb Public Class Form1 Dim connetionString As String Dim connection As OleDbConnection Dim oledbAdapter As OleDbDataAdapter Dim oledbCmdBuilder As OleDbCommandBuilder Dim ds As New DataSet Dim changes As DataSet Dim i As Integer Dim sql As String Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" connection = New OleDbConnection(connetionString) Sql = "select * from tblUsers" Try connection.Open() oledbAdapter = New OleDbDataAdapter(Sql, connection) oledbAdapter.Fill(ds) DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter) changes = ds.GetChanges() If changes IsNot Nothing Then oledbAdapter.Update(ds.Tables(0)) End If ds.AcceptChanges() MsgBox("Save changes") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class y

VB.NET ADO.NET DataView Tutorial


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

connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Sort DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price > 100", "Product_Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to Filter DataView


DataView enables you to create different views of the data stored in a DataTable. That is we can customize the views of data from a DataTable. DataView can be used to sort, filter, and search a DataTable , additionally we can add new rows and modify the content in a DataTable. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. Also we can create multiple DataViews for any given DataTable. The following source code creates a view that shows all Product Details where the Product Price less than 500. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Filter DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price < = 500", "Product_Name", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception

MsgBox(ex.ToString) End Try End Sub End Class

How to Find a row in DataView


The DataView provides different views of the data stored in a DataTable. The constructor for the DataView class initializes a new instance of the DataView class and accepts the DataTable as an argument. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable. We can search in a DataView according to the sort key values by using the Find method . The Find method returns an integer with the index of the DataRowView that matches the search criteria. If more than one row matches the search criteria, only the index of the first matching DataRowView is returned. If no matches are found, Find returns -1 Dim index As Integer = DataView.Find("Product5") Download Source Code 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() & " dv(index)("Product_Name").ToString()) End If 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 Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Add New") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) Dim newRow As DataRowView = dv.AddNew() newRow("Product_ID") = 7 newRow("Product_Name") = "Product 7" newRow("Product_Price") = 111 newRow.EndEdit() dv.Sort = "product_id" DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

How to update rows in DataView


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

We can update the data in a DataView . The following source code shows how to update data in a DataView . Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event. Download Source Code 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 Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String

connection As SqlConnection command As SqlCommand adapter As New SqlDataAdapter ds As New DataSet dv As DataView sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "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

Dim Dim Dim Dim Dim Dim

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

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

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

VB.NET Remoting Apllication


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

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

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

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

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

Compiling and Running Remote Application


The .NET Remoting is one of several ways to establish communication between application domains using the .NET Framework. The main three components of a Remoting Framework are a Remotable Object , Listener Application for listening requests for remote object and a Client Application makes requests for remote object. Additionally you need Configuration files for your Listener Application and Client Application. Compiling the VB.Net source code files Create a new folder SRC and put the three VB.Net source code files in that folder. 1. RemoteTime.vb 2. TimeListener.vb 3. Client.vb Add the two configuration files in the same folder. 1. TimeListener.exe.config 2. Client.exe.config Compile these VB.Net class files using the command-line tools that ship with the .NET Framework SDK. vbc /t:library RemoteTime.vb vbc /r:RemoteTime.dll TimeListener.vb vbc /r:RemoteTime.dll Client.vb Note: You have to provide the physical path of each source files when you compile the source code , for example : if the source code files are in the folder c:\SRC , you have to give path like vbc /r:c:\SRC\RemoteTime.dll c:\SRC\TimeListener.vb After you complied the VB.Net source code files, you will get additional three files in the SRC folder. They are : RemoteTime.dll TimeListener.exe Client.exe To run the application Create two new folders and give the name like Server and Client respectively. Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the Server folder.

Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder. Open a command prompt on Server folder and type TimeListener Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..." Open a command prompt on Client folder and type Client. Then you will get the current time from remote Object. Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more on Remoting ...

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

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

Click here to download Client.exe.config .

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

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

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

VB.NET XML Tutorial


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

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

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

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

How to search in an XML file


XML files are made up of tags that contains information. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format. The following source code shows how to search an item in an XML file using Dataset . Here Dataset using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. By using the Dataset , search the product Product2 in the file Product.XML with the help of DataView. Download Source Code Print Source Code 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() & " dv(index)("Product_Price").ToString()) End If End Sub 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 Dim Dim Dim Dim Dim Dim

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

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

How to create an Excel file from XML


XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify what the data it contains. Here we are going to read from an XML file content and write the same content to an Excel file. Using an XmlReader for read the XML file to the Dataset . Loop through the Dataset and add the content to the Excel file . For create an excel file you have to add reference of Excel library to you project . Download Source Code Print Source Code Imports System.Xml Imports System.Data Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim ds As New DataSet

Dim xmlFile As XmlReader Dim i, j As Integer xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile) For i = 0 To ds.Tables(0).Rows.Count - 1 For j = 0 To ds.Tables(0).Columns.Count - 1 xlWorkSheet.Cells(i + 1, j + 1) = _ ds.Tables(0).Rows(i).Item(j) Next Next xlWorkSheet.SaveAs("xml2excel.xlsx") xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub End Class Click here to download the input file product.xml

How to create an XML file from Excel


XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . The following program shows how to create an XML file from an Excel file content . Here we are using an OleDbConnection to read the excel file and store the content to a Dataset . Call the method WriteXml of Datset to write to the XML file. Download Source Code Print Source Code Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim MyConnection As System.Data.OleDb.OleDbConnection Dim ds As System.Data.DataSet Dim MyCommand As System.Data.OleDb.OleDbDataAdapter MyConnection = New System.Data.OleDb.OleDbConnection _ ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='xl2xml.xls';Extended Properties=Excel 8.0;")

MyCommand = New System.Data.OleDb.OleDbDataAdapter _ ("select * from [Sheet1$]", MyConnection) MyCommand.TableMappings.Add("Table", "Product") ds = New System.Data.DataSet MyCommand.Fill(ds) MyConnection.Close() ds.WriteXml("Product.xml") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class Click here to download the input excel file xl2xml.xls

How to xml to DataGridView


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


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

In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes data to TreeView. Download Source Code 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 XmlNode Dim fs As New FileStream("tree.xml", FileMode.Open, FileAccess.Read) xmldoc.Load(fs) xmlnode = xmldoc.ChildNodes(1) TreeView1.Nodes.Clear() TreeView1.Nodes.Add(New TreeNode(xmldoc.DocumentElement.Name)) Dim tNode As TreeNode tNode = TreeView1.Nodes(0) AddNode(xmlnode, tNode) End Sub Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As TreeNode) Dim xNode As XmlNode Dim tNode As TreeNode Dim nodeList As XmlNodeList Dim i As Integer If inXmlNode.HasChildNodes Then nodeList = inXmlNode.ChildNodes For i = 0 To nodeList.Count - 1 xNode = inXmlNode.ChildNodes(i) inTreeNode.Nodes.Add(New TreeNode(xNode.Name)) tNode = inTreeNode.Nodes(i) AddNode(xNode, tNode) Next Else inTreeNode.Text = inXmlNode.InnerText.ToString End If End Sub

End Class Click here to download the input file tree.xml

How to create Crystal Reports from XML


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

Crystal Reports from XML File


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

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

Select all the fields from Product and click finish button Now the designer part is over . Next step is to select the default form(Form1.vb) and add a Button and Crystal Reports Viewer to the Form. Put the following vb.net source code in your form and run the program . Download Source Code Print Source Code Imports CrystalDecisions.CrystalReports.Engine Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim cryRpt As New ReportDocument cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") CrystalReportViewer1.ReportSource = cryRpt CrystalReportViewer1.Refresh() End Sub End Class cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt") The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give the full path name of report here.

How to serialization in xml


XML Serialization is the process of serializing a .Net Object to the form of XML or from an XML to .Net Object. The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. This is the process of converting an object into a form that can be readily transported.

During XML serialization, only the public properties and fields of an object are serialized. The following links gives you more details about XML Serialization and De-serialization. How to serialize a .Net Object to XML 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 y

VB.NET DataGridView Tutorial


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

DataGridView binding - OLEDB in VB.NET


The DataGridView can display data in Bound mode and unbound mode and Virtual mode. The easiest way to get started using the DataGridView control is to use it in basic data binding scenarios. The DataGridView control can display rows of data from a data source. When you specify a data source for the DataGridView, by default it will construct columns for you automatically. This will be created based on the data types in the data source. The following vb.net program shows how to bind an OLEDB dataset in a DataGridView. Download Source Code

Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Your .mdb path";" Dim sql As String = "SELECT * FROM Authors" Dim connection As New OleDbConnection(connectionString) Dim dataadapter As New OleDbDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class

DataGridView Sorting/Filtering in VB.NET


The DataGridView control provides a customizable table for displaying data. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. A DataView provides a means to filter and sort data within a DataTable. The following vb.net program shows how to filter and sort a DataGridView by using a DataView Object. Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Download Source Code 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 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 Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).Visible = False End Sub End Class

DataGridView ReadOnly rows and columns in VB.NET

The DataGridView control can display rows of data from a data source. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The ReadOnly property indicates whether the data displayed by the cell can be edited or not. You can set ReadOnly Property in three levels. You can make entire dataGridView as ReadOnly. dataGridView1.ReadOnly = true You can make entire row as ReadOnly dataGridView1.Rows(index).ReadOnly = true; You can make entire Column as ReadOnly dataGridView1.Columns(index).ReadOnly = true; The following vb.net source code shows how to make a row as Readonly in a DataGridView. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).ReadOnly = True End Sub End Class

Adding Button to DataGridView in VB.NET


The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the corresponding cell types. With the DataGridViewButtonColumn, you can display a column of cells that contain buttons.You can respond to user clicks in button cells by handling the DataGridView.CellClick event. The following vb.net program shows how to add a Button in Cell of a DataGridView control. Also it showing in the DataGridView.CellClick event which button the user clicked. Download Source Code 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 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 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 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 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() DataGridView1.DataSource = pagingDS DataGridView1.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click scrollVal = scrollVal - 5 If scrollVal <= 0 Then scrollVal = 0

End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub End Class

How to Formatting in DataGridView

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

Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" DataGridView1.GridColor = Color.Red DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None DataGridView1.BackgroundColor = Color.LightGray DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True] DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect DataGridView1.AllowUserToResizeColumns = False DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End Sub End Class

How to DataGridView Template

There are situations that you want greater control over the appearance of DataGridView rows than what is provided by the various DataGridView cell style properties. The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set any DataGridViewRow properties, including DefaultCellStyle. When displaying external data, however, the rows are generated automatically, but they are based on the row template, which you can set to an instance of your custom row type.

The following vb.net code example illustrates how to use the row template to specify an initial row height and a minimum row height and BackColor. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim row As DataGridViewRow = Me.DataGridView1.RowTemplate row.DefaultCellStyle.BackColor = Color.Bisque row.Height = 35 row.MinimumHeight = 20 Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub

End Class How to DataGridView Printing

The DataGridView control provides a customizable table for displaying data. It gives you number of properties, methods and events to customize its appearance and behavior. Unfortunately the DataGridView doesn't have a built in printing functionality . So here we do a tricky way to print the content of DataGridView . Here we add a PrintDocument object to the project and handle the PrintPage event which is called every time a new page is to be printed. Here in the PrintPage event we create a Bitmap Object and draw the DataGridView to the Bitmap Object.

In order to run this vb.net project you have to drag two buttons ,one for load data and one for print command, and drag a PrintDocument control on your form . The following picture shows how to drag PrintDocument Object to your project. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim bm As New Bitmap(Me.DataGridView1.Width, Me.DataGridView1.Height) DataGridView1.DrawToBitmap(bm, New Rectangle(0, 0, Me.DataGridView1.Width, Me.DataGridView1.Height)) e.Graphics.DrawImage(bm, 0, 0) End Sub End Class

How to Export datagridview to Excel


The DataGridView control provides a customizable table for displaying data. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. The following vb.net source code shows how to Export the content of a datagridview to an Excel file. Download Source Code Imports System.Data.SqlClient Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close()

DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim i As Int16, j As Int16 xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") For i = 0 To DataGridView1.RowCount - 2 For j = 0 To DataGridView1.ColumnCount - 1 xlWorkSheet.Cells(i + 1, j + 1) = DataGridView1(j, i).Value.ToString() Next Next xlWorkBook.SaveAs("c:\vb.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _ Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue) xlWorkBook.Close(True, misValue, misValue) xlApp.Quit() releaseObject(xlWorkSheet) releaseObject(xlWorkBook) releaseObject(xlApp) MessageBox.Show("Over") End Sub Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing MessageBox.Show("Exception Occured while releasing object " + ex.ToString()) Finally GC.Collect() End Try End Sub End Class

How to Import data from Excel to DataGridView


The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data. You can use a DataGridView control to display data with or without an underlying data source. The following vb.net source code shows how to Import data from an Excel file to a DataGridView control . Download Source Code

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

Database operations in DatagridView

The DataGridView control can display rows of data from a data source. The DataGridView can display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for managing data using automatic interaction with the data store. One very common use of the DataGridView control is binding to a table in a database. Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. Virtual mode gives you a higher degree of control by allowing you to wait until a cell is actually being displayed to provide the value it will contain. The following vb.net source code illustrate how to connect a DataGridView to a database and addnew/update or delete the database values from DataGridView. Download Source Code Imports System.Data.SqlClient

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

asd

You might also like