ASP.NET Database Programming Guide
ASP.NET Database Programming Guide
Net
UNIT-IV
While working with databases, the following concepts which are common across all
databases.
1. Connection – To work with the data in a database, the first obvious step is the
connection. The connection to a database normally consists of the below-
mentioned parameters.
1. Database name or Data Source – The first important parameter is the
database name. Each connection can only work with one database at a
time.
2. Credentials – The next important aspect is the 'username' and 'password'.
This is used to establish a connection to the database.
3. Optional parameters - You can specify optional parameters on how .net
should handle the connection to the database. For example, one can
specify a parameter for how long the connection should stay active.
2. Selecting data from the database – Once the connection is established, data is
fetched from the database. [Link] has the ability to execute 'sql' select
command against the database. The 'sql' statement can be used to fetch data from
a specific table in the database.
3. Inserting data into the database – [Link] is used to insert records into the
database. Values for each row that needs to be inserted in the database are
specified in [Link].
4. Updating data into the database – [Link] can also be used to update existing
records into the database. New values can be specified in [Link] for each row
that needs to be updated into the database.
5. Deleting data from a database – [Link] can also be used to delete records
from the database. The code is written to delete a particular row from the
database.
2. Creating Connection
Let's now look at the code, which needs to be kept in place to create a connection to a
database. In our example, we will connect to a database which has the name of Demodb.
Username – sa
Password – demo123
Let's work with our current web application created in the earlier sections.
Step 1) Let's first ensure that you have your web application (DemoApplication) opened
in Visual Studio. Double click the '[Link]' file to enter the code for the database
connection.
Step 2) Add the below code which will be used to establish a connection to the database.
namespace DemoApplication
{
public partial class Demo [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
[Link]();
[Link]("Connection MAde");
[Link]();
}
}
}
Code Explanation:-
1. The first step is to create variables. It will be used to create the connection string
and the connection to the SQL Server database.
2. The next step is to actually create the connection string. The connection string
consists of the following parts
Data Source – This is the name of the server on which the database resides. In our
case, it resides on a machine called WIN- 50GP30FGO75.
The Initial Catalog is used to specify the name of the database
The UserID and Password are the credentials required to connect to the database.
4. Next, we use the open method of the cnn variable to open a connection to the
database. We display a message to the user that the connection is established. This
is done via the '[Link]' method. We then close the connection to the
database.
When the above code is set, and the project is executed using Visual Studio. You will get
the below output. Once the form is displayed, click the Connect button.
Output:-
The output message displayed in the browser will show that the connection to the
database is made.
3. [Link] Data Set
It is a collection of data tables that contain the data. It is used to fetch data without
interacting with a Data Source that's why, it also known as disconnected data access
method. It is an in-memory data store that can hold more than one table at the same time.
We can use DataRelation object to relate these tables. The Data Set can also be used to
read and write data as XML document.
[Link] provides a Data Set class that can be used to create Data Set object. It contains
constructors and methods to perform data related operations.
Constructor Description
Properties Description
DefaultViewManager It is used to get a custom view of the data contained in the DataSet
to allow filtering and searching.
HasErrors It is used to check whether there are errors in any of the DataTable
objects within this DataSet.
Method Description
Copy() It is used to copy both the structure and data for this
DataSet.
ReadXml(XmlReader, It is used to read XML schema and data into the DataSet
XmlReadMode) using the specified XmlReader and XmlReadMode.
Example:
Here, in this example, we are implementing DataSet and displaying data into a gridview.
Create a web form and drag a gridview from the toolbox to the form. We can find it
inside the data category.
// [Link]
CodeBehind
// [Link]
using System;
using [Link];
using [Link];
namespace DataSetExample
{
public partial class DataSetDemo : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=stu
dent; integrated security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
[Link](ds);
[Link] = ds;
[Link]();
}
}
}
}
4. [Link] Data Adapter
The Data Adapter works as a bridge between a Data Set and a data source to retrieve
data. Data Adapter is a class that represents a set of SQL commands and a database
connection. It can be used to fill the Data Set and update the data source.
Constructors Description
4.3 Methods
Method Description
Example
// [Link]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="[Link].
cs"
Inherits="[Link]" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" CellPadding="3" BackColor="#DE
BA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2"
>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-
Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-
Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</form>
</body> </html>
Code Behind
using System;
using [Link];
using [Link];
namespace DataSetExample
{
public partial class DataSetDemo : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=stud
ent; integrated security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
[Link](ds);
[Link] = ds;
[Link]();
}
}
}
}
Output:
5. [Link] Read Database using SqlDataReader
To show data accessed using [Link], let us assume the following artifacts in our
database.
1. A table called demotb. This table will be used to store the ID and names of
various Tutorials.
2. The table will have two columns, one called "TutorialID" and the other called
"TutorialName."
3. For the moment, the table will have two rows as shown below.
TutorialID TutorialName
1 C#
2 [Link]
Let's change the code so that we can query for this data and display the information on
the web page itself. Note that the code entered is in continuation to that written for the
data connection module.
The first part will be to construct our "select" statement. It will be used to read the
data from the database.
We will then execute the "select" statement against the database. This will fetch
all the table rows accordingly.
Code Explanation:-
2. The next step is to actually define the SQL statement. This will be used against
our database. In our case, it is "Select TutorialID, TutorialName from demotb".
This will fetch all the rows from the table demotb.
3. Next, we create the command object which is used to execute the SQL statement
against the database. In the SQL command, you have to pass the connection
object and the SQL string.
4. Next, we will execute the data reader command, which will fetch all the rows
from the demotb table.
5. Now that we have all the rows of the table with us, we need a mechanism to
access the row one by one.
Step 2) In the final step, we will just display the output to the user. Then we will close all
the objects related to the database operation.
namespace DemoApplication
{
public partial class Demo [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand command;
SqlDataReader dataReader;
String sql, Output =" ";
sql = "Select TutorialID,TutorialName from demotb";
dataReader = [Link]();
while ([Link]())
{
Output = Output + [Link](0) + "-" +
[Link](1) + "</br>";
}
[Link](Output);
[Link]();
[Link]();
[Link]();
}
}
}
Code Explanation:-
1. We will continue our code by displaying the value of the Output variable. This is
done using the [Link] method.
2. We finally close all the objects related to our database operation. Remember this
is always a good practice.
When the above code is set, and the project is run using Visual Studio, you will get the
below output.
Output:-
From the output, you can clearly see that the program was able to get the values from the
database. The data is then displayed in the browser to the user.
6. Database Operations
6.1 Insert into Database
Just like Accessing data, C# has the ability to insert records into the database as well. To
showcase how to insert records into our database, let's take the same table structure which
was used above.
TutorialID TutorialName
1 C#
2 [Link]
Let's change the code in our form, so that we can insert the following row into the table
TutorialID TutorialName
3 [Link]
So let's add the following code to our program. The below code snippet will be used to
insert an existing record in our database.
Code Explanation:-
When the above code is set, and the project is executed using Visual Studio, you will get
the below output. Once the form is displayed, click the Connect button.
Output:-
If you go to SQL Server Express and see the rows in the demotb table, you will see the
row inserted as shown below
1 C#
2 [Link]
3 [Link]
Let's change the code in our form, so that we can update the following row. The old row
value is TutorialID as "3" and Tutorial Name as "[Link]". Which we will update it to
"[Link] complete" while the row value for Tutorial ID will remain same.
Old row
TutorialID TutorialName
3 [Link]
New row
TutorialID TutorialName
3 [Link] complete
So let's add the following code to our program. The below code snippet will be used to
update an existing record in our database.
Code Explanation:-
When the above code is set, and the project is executed using Visual Studio, you will get
the below output. Once the form is displayed, click the Connect button.
Output:-
If you actually go to SQL Server Express and see the rows in the demotb table, you will
see the row was successfully updated as shown below.
TutorialID TutorialName
1 C#
2 [Link]
3 [Link] complete
Let's change the code in our form, so that we can delete the following row
TutorialID TutorialName
3 [Link] complete
So let's add the following code to our program. The below code snippet will be used to
delete an existing record in our database.
Code Explanation:-
1. The Key difference in this code is that we are now issuing the delete SQL
statement. The delete statement is used to delete the row in the demotb table in
which the TutorialID has a value of 3.
2. In our data adapter command, we now associate the insert SQL command to our
adapter. We also then issue the ExecuteNonQuery method which is used to
execute the Delete statement against our database.
When the above code is set, and the project is executed using Visual Studio, you will get
the below output. Once the form is displayed, click the Connect button.
Output:-
If you actually go to SQL Server Express and see the rows in the demotb table, you will
see the row was successfully deleted as shown below.
Data binding is binding controls to data from databases. With data binding we can bind a
control to a particular column in a table from the database or we can bind the whole table
to the data grid. Data binding provides simple, convenient, and powerful way to create a
read/write link between the controls on a form and the data in their application.
Data binding allows you to take the results of properties, collection, method calls, and
database queries and integrate them with your [Link] code. You can combine data
binding with Web control rendering to relieve much of the programming burden
surrounding Web control creation. You can also use data binding with [Link] and
Web controls to populate control contents from SQL select statements or stored
procedures.
The <%#, which instructs [Link] to evaluate the expression. The difference between a
data binding tags and a regular code insertion tags <% and %> becomes apparent when
the expression is evaluated. Expressions within the data binding tags are evaluated only
when the DataBind method in the Page objects or Web control is called.
Data Bind Control can display data in connected and disconnected model.
Repeater Control
DataGrid Control
DataList Control
GridView Control
DetailsView
FormView
DropDownList
ListBox
RadioButtonList
CheckBoxList
BulletList
etc.
To display backend result set (tuple collection) Repeater Control, DataGrid Control,
DataList Control, GridView Control are used.
Repeater Control, DataList Control and FormView Control are unformatted controls.
In simple data binding, the control is bounded to a data set. The properties of the control
are used for binding with the value. Depending on the control to be bounded, the
binding’s property is set.
The process of binding a component like listbox, DataGrid, record list with the dataset is
known as declarative binding. When there is more than one element in the database, the
declarative binding is used.
Some of the controls used for the declarative data binding are listed below.
1. DataGrid: The data from multiple records is displayed using the DataGrid view.
The DataSource property of the control is used for binding the specific element
data.
2. ListBox: The data for a column from different dataset is displayed. The
DataSource property is used for binding the control. The control binds to the
specific element using the DisplayMember property.
3. ComboBox: The DisplayMember property is used for binding the control to the
specific data element. The DataSource property is used for binding the control to
the data source.
C# and Visual Studio have inbuilt data grids, this can be used to display data. Let's take a
look at an example of this. In our example, we will have a data grid, which will be used
to display the Tutorial ID and Tutorial Name values from the demotb table.
Step 1) Drag the DataGridView control from the toolbox to the Form in Visual Studio.
The DataGridView control is used in Visual Studio to display the rows of a table in a
grid-like format.
Step 2) In the next step, we need to connect our data grid to the database. In the last
section, we had created a project data source. Let's use the same data source in our
example.
1. First, you need to choose the grid and click on the arrow in the grid. This will
bring up the grid configuration options.
2. In the configuration options, just choose the data source as demotbBindingSource
which was the data source created in the earlier section.
If all the above steps are executed as shown, you will get the below-mentioned output.
Output:-
From the output, you can see that the grid was populated by the values from the database.
There can be several ways to connect to a database through C#. Here, I have covered a
simple [Link] approach and I have done this through Stored Procedure and Grid
View. So it will be good to have a little knowledge of SQL server and [Link] prior to
going for this. I have used Visual Studio 2012 and SQL Server 2012, but the code will be
the same for all the Visual Studio and SQL Server versions.
Add a new project and give a name to it (In my case, the name is DatabaseConnectivity)
as shown below:
Add a new Web Form with Master Page and give a name (In my case, the name
is [Link]) and select Master Page as below:
The next step is to create a Registration Form as below and add the below code inside
Content Place holder whose Id is Content3 as below:
<asp:Content ID="Content3"
ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td>
Name
</td>
<td>
<asp:TextBox ID="txtName"
runat="server"
required="true"></asp:TextBox>
</td>
</tr> <tr>
<td>
Email
</td>
<td>
<asp:TextBox ID="txtEmail"
runat="server" required="true"
type="Email"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<asp:TextBox ID="txtPassword"
runat="server" required="true"
type="Password"></asp:TextBox>
</td>
</tr> <tr>
<td>
Confirm Password
</td>
<td>
<asp:TextBox ID="txtConfirmPassword"
runat="server" required="true"
type="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Address
</td>
<td>
<asp:TextBox ID="txtAddress"
runat="server" required="true"
TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit"
Run the application after setting this page as a Start Page (Right click
on [Link] and click on Set as Start page). Once run, we will get a page as
below.
The next step is to generate a Button Click Event. For this, just right click on the Button
and go to Properties and double click on click event (or directly double click on the
button).
Once you will double click on the button, an event will generated on the code behind
page as below:
Whatever you want to perform when you will click on Button, you will write inside this
click event. In our case, we will do database connectivity here and will save all the values
in database. For this, I created a database named "Database Connectivity" and a table
inside it named "tblUser" with the below script:
This script will create a table in database having identity column in ID with Primary key.
I will use Stored Procedure for this, so create a stored procedure as below:
using [Link];
using [Link];
con is the object of SQL Connection Class. In Connection String, the meanings of
different attributes are:
Data Source: In Data Source, we will provide the Machine Name where we create the
database. (.) Means Database is in your local Machine.
Initial Catalog: Initial Catalog is the database Name (In my case, it
is DatabaseConnectivity).
Trusted_Connection: Trusted_Connection should be true if you are using window
authentication while connecting to database. If you are using SQL authentication, you
will have to pass userid and password.
[Link]();
To prepare a command, [Link] gives us a class named SqlCommand which we will use as
below:
[Link]();
try
{
[Link]();
// Create a object of SqlCommand class
[Link] = con; //Pass the connection object to Command
[Link] = [Link]; // We will use
stored procedure.
[Link] = "spInsertUser"; //Stored Procedure Name
[Link]();
}
catch (Exception ex)
{
}
finally
{
[Link]();
}
}
Run the application and fill the form and click on submit:
Note: I have created a project with insert operation in a database if you want to
perform more operations on database then follow the database operations topic
from the same unit.
References:
[Link]
[Link]
Net/
[Link]
[Link]
NET-Csharp-with-SQL