VB 5
VB 5
VB 5
Database management systems provide APIs that allow application programmers to create and access
databases. The set of APIs that each manufacturer's system supplies is unique to that manufacturer.
Microsoft has long recognized that it is inefficient and error prone for an applications programmer to
attempt to master and use all the APIs for the various available database management systems. What's
more, if a new database management system is released, an existing application can't
make use of it without being rewritten to understand the new APIs. What is needed is a common
database API. Microsoft's previous steps in this direction included Open Database Connectivity (ODBC),
OLE DB, and ADO (not to be confused with ADO.NET). Microsoft has made improvements with each new
technology. With .NET,
Microsoft has released a new mechanism for accessing data: ADO.NET. The name is
a carryover from Microsoft's ADO (ActiveX Data Objects) technology, but it no longer stands for ActiveX
ADO.NET Introduction
• It is a module of .Net Framework which is used to establish connection between application and
data sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that
can be used to connect, retrieve, insert and delete data.
• All the ADO.NET classes are located into System.Data.dll and integrated with XML classes
located into System.Xml.dll.
• ADO.NET has two main components that are used for accessing and manipulating data are
the .NET Framework data provider and the DataSet.
These are the components that are designed for data manipulation and fast access to data. It provides
various objects such as Connection, Command, DataReader and DataAdapter that are used to perform
database operations. We will have a detailed discussion about Data Providers in new topic.
Using SQL to work with database, Retrieving and manipulating data with SQL
You can connect your VB.Net application to data in a SQL Server database using the Microsoft
.NET Framework Data Provider for SQL Server. The first step in a VB.Net application is to create an
instance of the Server object and to establish its connection to an instance of SQL Server.
Connecting to a Database
Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please
consult 'SQL Server' tutorial for creating databases and database tables in SQL Server.
●Select a server name and the database name in the Add Connection dialog box
Add a DataGridView on the form.
When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will
show the following window −
Example 2
In this example, let us access data in a DataGridView control using code. Take the following steps −
●Add a DataGridView control and a button in the form.
●Double click the button control to add the required code for the Click event of the button, as shown
below −
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS' table.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
Me.Text = "tutorialspoint.com"
End Sub
connection.Open()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
● When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Clicking the Fill button displays the table on the data grid view control –
We have discussed that the DataSet components like DataTable, DataColumn and DataRow allow us to
create tables, columns and rows, respectively.
Example 3
So far, we have used tables and databases already existing in our computer. In this example, we will
create a table, add columns, rows and data into it and display the table using a DataGridView object.
Me.Text = "tutorialspont.com"
End Sub
dataset.Tables.Add(Students)
Return dataset
End Function
Return Students
End Function
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
● When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Clicking the Fill button displays the table on the data grid view control –
Working with ADO.NET, ADO.NET architecture
What is ADO.NET?
ADO stands for Active Data Objects. ADO is nothing but a component in .NET Framework that helps us to
fetch data from different data sources to our C# and VB.NET code and probably you can send data from
your C# or VB.NET code to different data sources.
1. Connection
2. Command
3. DataReader
4. DataAdapter
5. DataSet
6. DataView
From the above components, two components are compulsory. One is the command object and the
other one is the connection object. Irrespective of the operations like Insert, Update, Delete and Select,
the command and connection object you always need. For better understanding, please have a look at
the following image.
The first important component is the connection object. The connection object is required toconnect
with your backend database which can be SQL Server, Oracle, MySQL, etc. To create a connection
object, you need at least two things. The first one is where is your database located i.e. the Machine
name or IP Address or someplace where your database is located. And the second thing is the security
credentials i.e. whether it is a windows authentication or user name and password-based
authentication. So, the first is to create the connection object and the connection is required to connect
to the backend data source.
Command:
The second important component is the command object. When we talk about databases like SQL
Server, Oracle, MySQL, then understand SQL. The command object is the component where you go and
write your SQL queries. Later you take the command object and execute it
over the connection. Then you can fetch data or send data to the database using the command object
and SQL queries.
Note: From the command object onwards, you can go in two different ways. One is you can go with the
DataSet way and the other is, you can go with the DataReader way. Which way you need to choose,
basically it will depend on the situation.
DataReader:
DataReader is a read-only connected recordset that helps us to read the records only in the forward
mode. Here, you need to understand three things i.e. read-only, connected, and forward mode.
DataSet:
It is a disconnected recordset that can be browsed in both i.e. forward and backward. It is also possible
to update via dataset. DataSet gets filled by somebody called DataAdapter.
DataAdapter:
The DataAdapter acts as a bridge between the command object and the dataset. What the DataAdapter
does, it takes the data from the command object and fills the data set.
DataView Class
A DataView enables you to create different views of the data stored in a DataTable, a capability that is
often used in data-binding applications. Using a DataView, you can expose the data in a table with
different sort orders, and you can filter the data by row state or based on a filter expression.
● DataList
● DetailsView
● FormView
● GridView
● ListView
● Repeater
A data source control interacts with the data-bound controls and hides the complex data binding
processes. These are the tools that provide data to the data bound controls and support execution of
operations like insertions, deletions, sorting, and updates.
Each data source control wraps a particular data provider-relational databases, XML documents, or
custom classes and helps in:
● Managing connection
● Selecting data
● Managing presentation aspects like paging, caching, etc.
● Manipulating data
There are many data source controls available in ASP.NET for accessing data from SQL Server, from
ODBC or OLE DB servers, from XML files, and from business objects.
Based on type of data, these controls could be divided into two categories:
● XMLDataSource - It allows binding to XML files and strings with or without schema information.
● SiteMapDataSource - It allows binding to a provider that supplies site map information. The data
source controls used for tabular data are:
Data source views are objects of the DataSourceView class. Which represent a customized view of data
for different data operations such as sorting, filtering, etc.
The DataSourceView class serves as the base class for all data source view classes, which define the
capabilities of data source controls.
The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle
database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data
is made through two important properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax of the control:
Configuring various data operations on the underlying data depends upon the various properties
(property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource control, which provides
the programming interface of the control:
The following code snippet shows a data source control enabled for data manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
.....
.....
</asp:SqlDataSource>
he ObjectDataSource Control enables user-defined classes to associate the output of their methods to
data bound controls. The programming interface of this class is almost same as the SqlDataSource
control.
● The bindable class should have a default constructor, it should be stateless, and have methods
that can be mapped to select, update, insert, and delete semantics.
● The object must update one item at a time, batch operations are not supported.
Let us go directly to an example to work with this control. The student class is the class to be used with
an object data source. This class has three properties: a student id, name, and city. It has a default
constructor and a GetStudents method for retrieving data.
● Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a
class template, and placing the above code in it.
● Build the solution so that the application can use the reference to the class.
Select a data method(s) for different operations on data. In this example, there is only one method
Place a data bound control such as grid view on the page and select the object data source as its
underlying data source
At this stage, the design view should look like the following
Run the project, it retrieves the hard coded tuples from the students class
The AccessDataSource Control
</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it can also be used for
performing insert, update, or delete operations. This is done using the ADO.NET commands and
parameter collection.
Updates are problematic for Access databases from within an ASP.NET application because an Access
database is a plain file and the default account of the ASP.NET application might not have the
permission to write to the database file
●Local deployment : In this case, the entire application is contained within a virtual directory and all the
contents and assemblies are contained within it and available to the application.
●Global deployment : In this case, assemblies are available to every application running on the server.
There are different techniques used for deployment, however, we will discuss the following most
common and easiest ways of deployment:
● XCOPY deployment
● Copying a Website
XCOPY deployment means making recursive copies of all the files to the target folder on the target
machine. You can use any of the commonly used techniques:
● FTP transfer
XCOPY deployment simply copies the application file to the production server and sets a virtual directory
there. You need to set a virtual directory using the Internet Information Manager Microsoft
Management Console (MMC snap-in).
Copying a Website
The Copy Web Site option is available in Visual Studio. It is available from the Website -> Copy Web Site
menu option. This menu item allows copying the current web site to another local or remote location. It
is a sort of integrated FTP tool.
Using this option, you connect to the target destination, select the desired copy mode:
● Overwrite
Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of
deployment is done from Visual Studio environment. However, there are following problems with both
the above deployment methods:
In this method, you use Windows Installer and package your web applications so it is ready to deploy on
the production server. Visual Studio allows you to build deployment packages. Let us test this on one of
our existing project, say the data binding project.
Step (1) : Select File -> Add -> New Project with the website root directory highlighted in the Solution
Explorer.
Step (2) : Select Setup and Deployment, under Other Project Types. Select Setup Wizard.
Step (3) : Choosing the default location ensures that the set up project will be located in its own folder
under the root directory of the site. Click on okay to get the first splash screen of the wizard
Step (4) : Choose a project type. Select 'Create a setup for a web application'.
Step (5) : Next, the third screen asks to choose project outputs from all the projects in the solution.
Check the check box next to 'Content Files from...'
Step (6) : The fourth screen allows including other files like ReadMe. However, in our case there is no
such file. Click on finish
Step (7) : The final screen displays a summary of settings for the set up project.
Step (8) : The Set up project is added to the Solution Explorer and the main design window shows a file
system editor.
Step (9) : Next step is to build the setup project. Right click on the project name in the Solution Explorer
and select Build.
Step (10) : When build is completed, you get the following message in the Output window:
● Setup-databinding.msi
You need to copy these files to the server. Double-click the setup file to install the content of the
Most applications are data-centric, however most of the data repositories are relational databases. Over
the years, designers and developers have designed applications based on object models.
The objects are responsible for connecting to the data access components - called the Data Access Layer
(DAL). Here we have three points to consider:
● All the data needed in an application are not stored in the same source. The source could be a
relation database, some business object, XML file, or a web service.
• Accessing in-memory object is simpler and less expensive than accessing data from a database
or XML file.
• The data accessed are not used directly, but needs to be sorted, ordered, grouped, altered etc.
• Hence if there is one tool that makes all kind of data access easy that allows joining data from
such disparate data sources and perform standard data processing operations, in few lines of
codes, it would be of great help.
• LINQ or Language-Integrated Query is such a tool. LINQ is set of extensions to the .Net
Framework 3.5 and its managed languages that set the query as an object. It defines a common
syntax and a programming model to query different types of data using a common language.
• The relational operators like Select, Project, Join, Group, Partition, Set operations etc., are
implemented in LINQ and the C# and VB compilers in the .Net framework 3.5, which support the
LINQ syntax makes it possible to work with a configured data store without resorting to
ADO.NET.
For example, querying the Customers table in the Northwind database, using LINQ query in C#, the code
would be:
select c; Where:
• The 'from' keyword logically loops through the contents of the collection.
• The expression with the 'where' keyword is evaluated for each object in the collection.
• The 'select' statement selects the evaluated object to add to the list being returned.
• The 'var' keyword is for variable declaration. Since the exact type of the returned object is not
known, it indicates that the information will be inferred dynamically.
• LINQ query can be applied to any data-bearing class that inherits from IEnumerable<T>, here T is
any data type, for example, List<Book>.
Let us look at an example to understand the concept. The example uses the following class:
Books.cs
Price = 634.76m,
Price = 250.76m,
Price = 700.00m,
Price = 500.99m,
Price = 456.76m,
Price = 1000.76m,
return list;
}}
The web page using this class has a simple label control, which displays the titles of the books. The
Page_Load event creates a list of books and returns the titles by using LINQ query:
When the page is executed, the label displays the results of the query:
The above LINQ expression:
LINQ Operators
Apart from the operators used so far, there are several other operators, which implement all query
clauses. Let us look at some of the operators and clauses.
The 'join clause' in SQL is used for joining two data tables and displays a data set containing columns
from both the tables. LINQ is also capable of that. To check this, add another class named Saledetails.cs
in the previous project:
};
return sd.OfType<Salesdetails>();
Add the codes in the Page_Load event handler to query on both the tables using the join clause:
protected void Page_Load(object sender, EventArgs e)
{
The 'where clause' allows adding some conditional filters to the query. For example, if you want to see
the books, where the number of pages are more than 500, change the Page_Load event handler to:
where s.pages > 500 select new { Name = b.Title, Pages = s.pages };
The query returns only those rows, where the number of pages is more than 500:
Orderby and Orderbydescending Clauses
These clauses allow sorting the query results. To query the titles, number of pages and price of the book,
sorted by the price, write the following code in the Page_Load event handler:
orderby b.Price select new { Name = b.Title, Pages = s.pages, Price = b.Price}; The returned tuples are:
The let clause allows defining a variable and assigning it a value calculated from the data values. For
example, to calculate the total sale from the above two sales, you need to calculate:
To achieve this, add the following code snippets in the Page_Load event handler:
The let clause allows defining a variable and assigning it a value calculated from the data values. For
example, to calculate the total sale from the above two sales, you need to calculate:
LINQ to Objects offers usage of any LINQ query supporting IEnumerable<T>for accessing in-memory
data collections without any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to XML.
• In short, LINQ to Objects offers a fresh approach to collections as earlier, it was vital to write
long coding (foreach loops of much complexity) for retrieval of data from a collection which is
now replaced by writing declarative code which clearly describes the desired data that is
required to retrieve.
• There are also many advantages of LINQ to Objects over traditional foreach loops like more
readability, powerful filtering, capability of grouping, enhanced ordering with minimal
application coding. Such LINQ queries are also more compact in nature and are portable to any
other data sources without any modification or with just a little modification.
using System.Text;
namespace LINQtoObjects {
class Program {
LINQ to Objects offers usage of any LINQ query supporting IEnumerable<T>for accessing in-memory
data collections without any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to XML.
• In short, LINQ to Objects offers a fresh approach to collections as earlier, it was vital to write
long coding (foreach loops of much complexity) for retrieval of data from a collection which is
now replaced by writing declarative code which clearly describes the desired data that is
required to retrieve.
• There are also many advantages of LINQ to Objects over traditional foreach loops like more
readability, powerful filtering, capability of grouping, enhanced ordering with minimal
application coding. Such LINQ queries are also more compact in nature and are portable to any
other data sources without any modification or with just a little modification.
using System.Text;
namespace LINQtoObjects {
class Program {
sb.Append(s + Environment.NewLine);
Console.WriteLine(sb.ToString(), "Tools");
Console.ReadLine();
In the example, an array of strings (tools) is used as the collection of objects to be queried using LINQ to
Objects.
Objects query is:
When the above code is compiled and executed, it produces the following result − Tablesaw
Bandsaw
Next
Console.ReadKey()
End Sub
Class Department
End Class
End Module
When the above code of C# or VB is compiled and executed, it produces the following result −
Department Id = 1, Department Name = Account
LINQ to XML
LINQ to XML offers easy accessibility to all LINQ functionalities like standard query operators,
programming interface, etc. Integrated in the .NET framework, LINQ to XML also makes the best use
of .NET framework functionalities like debugging, compile-time checking, strong typing and many more
to say.
While using LINQ to XML, loading XML documents into memory is easy and more easier is querying and
document modification. It is also possible to save XML documents existing in memory to disk and to
serialize them. It eliminates the need for a developer to learn the XML query language which is
somewhat complex.
LINQ to XML has its power in the System.Xml.Linq namespace. This has all the 19 necessary classes to
work with XML. These classes are the following ones.
● XAttribute
● XCData
● XComment
● XContainer
● XDeclaration
● XDocument
● XDocumentType
● XNamespace
LINQ to ADO.NET
Here we will see how to use LINQ to ADO.NET with the example for that we will create one new web
application and make the connection with the SQL SERVER and write the queries on ADO.NET object
(dataset) using LINQ to display the data in grid view.
Here first, we will create one new table "EmployeeDetails" in the database for that we will execute the
following query in our database and insert some dummy data to show it in the application.
Now we will create a new web application for that Go to File->Select New->Select Project, as shown
below.
After selecting the new project, a popup will open in that we have to choose asp.net empty Web
Application and give the name as LINQ to ADO.NET and click ok to create a new web application.
Now we will add the web page to the application for that we have to the right click on the application->
Select Add->Select Web Form->Give name as "Default.aspx" and click the ok button, it will create a new
page in the application.
Now open the "Default.aspx" page and write the code as shown below.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<Columns>
</Columns>
</asp:GridView>
</div>
</form></body></html>
using System.Data.SqlClient; using System.Linq;
using System.Web.UI.WebControls;
{ if (!Page.IsPostBack){
BindGridview();
} }
{ con.Open();
con.Close();
if (ds.Tables[0].Rows.Count > 0)
};
}}} }
In the above example, we used the ADO.NET dataset object and write the LINQ query on the dataset
object to get the details from the dataset where Gender is equal to "Female". Now we will run the
application and see the output
LINQ Query Syntax
There are two basic ways to write a LINQ query to IEnumerable collection or IQueryable data sources.
Query syntax is similar to SQL (Structured Query Language) for the database. It is defined within the C#
or VB code.
The LINQ query syntax starts with from keyword and ends with select keyword. The following figure
shows the structure of LINQ query syntax.
Query syntax starts with a From clause followed by a Range variable. The From clause is structured like
"From rangeVariableName in IEnumerablecollection". In English, this means, from each object in the
collection. It is similar to a foreach loop: foreach(Student s in studentList).
After the From clause, you can use different Standard Query Operators to filter, group, join elements of
the collection. There are around 50 Standard Query Operators available in LINQ. In the above figure, we
have used "where" operator (aka clause) followed by a condition. This condition is generally expressed
using lambda expression.
LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the
data. You can select the whole object as it is or only some properties of it. In the above example, we
selected the each resulted string elements.
In the following example, we use LINQ query syntax to find out teenager students from the Student
collection (sequence).
// Student collection
New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13}, New Student() With {.StudentID
= 2, .StudentName = "Moin", .Age = 21}, New Student() With {.StudentID = 3, .StudentName = "Bill", .Age
= 18}, New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20}, New Student() With
{.StudentID = 5, .StudentName = "Ron", .Age = 15}
Points to Remember :
1. As name suggest, Query Syntax is same like SQL (Structure Query Language) syntax.
2. Query Syntax starts with from clause and can be end with Select or GroupBy clause.
3. Use various other opertors like filtering, joining, grouping, sorting operators to construct the
desired result.
4. Implicitly typed variable - var can be used to hold the result of the LINQ query.
Stored Procedures
The data provider is a set of components that include the Connection, Command, DataReader, and
DataAdapter Objects. The command Object provides a number of Execute methods that can be used to
perform the SQL queries in a variety of fashions.
A stored procedure is a precompiled executable object that contains one or more SQL statements. A
sample Stored Procedure is given below :
The above code create a procedure named as 'SPPUBLISHER' and it execute SQL statement that select all
publisher name from publishers table from the PUB database.
Using stored procedures, database operations can be encapsulated in a single command, optimized for
best performance, and enhanced with additional security. To call a stored procedure from VB.NET
application, set the CommandType of the Command object to StoredProcedure.
From the following source code you can see how to call a stored procedure from VB.NET application.
Imports System.Data.SqlClient Public Class Form1
Dim i As Integer
Next connection.Close()