Beruflich Dokumente
Kultur Dokumente
OleDbConnection
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
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
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.
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.
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.
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.
" &
End While reader.Close() cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;" sql = "Your SQL Statement Here like Select * from product" You have to replace the string with your realtime variables.
DataReader = 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
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.
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.
" &
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.
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.
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.
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.
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. -" &
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.
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.
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.
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.
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 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.
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.
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 -" &
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.
--
" &
--
" &
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.
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.
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.
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
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
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
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
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
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
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
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
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
" &
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
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
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.
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.
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
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
Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder. Open a command prompt on Server folder and type TimeListener Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..." Open a command prompt on Client folder and type Client. Then you will get the current time from remote Object. Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more on Remoting ...
Remoting Configurations
Configuration provides the necessary information to .Net Remoting Framework . We can provide .Net Remoting configuration parameters in two ways. Either we can provide the information to the Server and the Client directly by program coding or through a Machine.config file. Using configuration file give better advantage over coding because the parameters of remote object can be configured without changing any program coding and avoid recompile the source code. Following are the information provided by configuration file : Metadata describing the Remote Type Type of Activation Channels The URL that uniquely identifies the object of that type. We have to provide configuration information to Listener Object and also Client Object . Listener Configuration
Remoting Activation
The .Net Remoting framework supports Server and Client activation of Remote Objects. Before an Object instance of a Remotable type can be accessed, it must be created and initialized by Activation process. There are commonly two types of activation modes : Server Activation and Client Activation mode. Server activation is normally used when a Remote objects is not required to maintain any state between method calls. Client Activated objects are instantiated from the client, and the client manages the lifetime of the Remote Object by using a lease-based system provided for that purpose. SingleCall Objects and Singleton Objects belong to Server Activation mode. For SingleCall objects the server will create a single object, execute the method, and destroy the object again. On the other hand with Singleton mode only one object is created at all. Singleton objects can be used to share information between multiple clients. The real distinction between Client Activated and Server Activated object is that a server-activated object is not really created when a client instantiates it. Instead, it is created as needed.
Remoting Channel
In .Net Remoting Channels are used to transport messages to and from the Remote Objects. Channels are Objects that responsible of handling the network protocols and serialization formats. In .Net Remoting channel can be implement either by calling the method ChannelServices.RegisterChannel or by using configuration file. Channels should be registered before objects are registered. When a channel is registered, it automatically starts listening for client requests at the specified port. At least one channel must be registered with the remoting framework before a Remote object can be called. There are two types of Channels available in .Net Remote Framework: HTTP channel and TCP channel. The HTTP channel transports messages to and from remote objects using the SOAP protocol. The TCP channel uses a binary formatter to serialize all messages to a binary stream and transport the stream to the target URI using the TCP protocol.
Remoting Channel
Formatters are used for encoding and decoding the messages before they are transported by the Channel in .Net Remoting Framework. The .Net Remoting Framework supports two types of Formatters : Binary Formatter System.Runtime.Serialization.Formatters.Binary and SOAP Formatter - System.Runtime.Serialization.Formatters.Soap . The data in binary Formatter has smaller size when compared to SOAP Formatter. The SOAP Formatter is an XML based cross platform text format , so it can be human readable. The data in a SOAP Formatter larger size compared to Binary Formatter , so it can therefore reduce overall performance.
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.
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 :
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
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
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.
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
" &
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
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
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
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
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.
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
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
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
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
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
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
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
The DataGridView class allows customization of cells, rows, columns, and borders through the use of its properties . If a DataGridView has lot of rows then we can implement paging functionalities to the DataGridView control. While we implement paging we should know the boundaries of the pages to enable the paging in the DatagridView. The following vb.net program provides a way to programmatically implement paging in a Windows Datagrid View control. Here the DataGridView rows fixed as five rows and other two buttons are there for implementing paging functionalities. Download Source Code Imports System.Data.SqlClient Public Class Form1 Dim pagingAdapter As SqlDataAdapter Dim pagingDS As DataSet Dim scrollVal As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM authors" Dim connection As New SqlConnection(connectionString) pagingAdapter = New SqlDataAdapter(sql, connection) pagingDS = New DataSet() connection.Open() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") connection.Close() DataGridView1.DataSource = pagingDS DataGridView1.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click scrollVal = scrollVal - 5 If scrollVal <= 0 Then scrollVal = 0
End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub End Class
The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. The DataGridView control makes it easy to define the basic appearance of cells and the display formatting of cell values. Typically, however, multiple cells will share particular style characteristics. You can define appearance and formatting styles for individual cells, for cells in specific columns and rows, or for all cells in the control by setting the properties of the DataGridViewCellStyle objects accessed through various DataGridView control properties. The following vb.net program shows how to implement different ways of cell formatting in a DataGridView control. Download Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" DataGridView1.GridColor = Color.Red DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None DataGridView1.BackgroundColor = Color.LightGray DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True] DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect DataGridView1.AllowUserToResizeColumns = False DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End Sub End Class
There are situations that you want greater control over the appearance of DataGridView rows than what is provided by the various DataGridView cell style properties. The row template gives you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle property provides. With the row template, you can set any DataGridViewRow properties, including DefaultCellStyle. When displaying external data, however, the rows are generated automatically, but they are based on the row template, which you can set to an instance of your custom row type.
The following vb.net code example illustrates how to use the row template to specify an initial row height and a minimum row height and BackColor. Download Source Code 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
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
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
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
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