Practical PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

1. ASP.

NET First Program Example: Hello World


Step 1) The first step involves the creation of a new project in Visual Studio. After launching
Visual Studio, you need to choose the menu option New->Project.

Step 2) The next step is to choose the project type as an ASP.Net Web application. Here we also
need to mention the name and location of our project.
1. In the project dialog box, you can see various options for creating different types of projects.
Click the Web option on the left-hand side.
2. When we click the Web option in the previous step, we will be able to see an option for
ASP.Net Web Application. Click this option.
3. We then give a name for the application, which in our case is DemoApplication. We also
need to provide a location to store our application.
4. Finally, we click the 'OK' button to let Visual Studio to create our project.
Step 3) In the next screen, you have to choose the type of ASP.net web application that needs to be
created. In our case, we are going to create a simple Web Form application.
1. First, choose the project type as 'Empty'. This will ensure that we start with a basic
application which is simple to understand.
2. We choose the option "web Forms". This adds the basic folders. These are required for a
basic Web Forms Application.
3. Finally, we click the 'OK' button to allow Visual Studio to create our application.
If the above steps are followed, you will get the below output in Visual Studio.
Output:-

In the Solution Explorer, you will be able to see the DemoApplication Solution. This solution will
contain 2 project files as shown above. At the moment, one of the key files in the project is the
'Global.asax.cs'. This file contains application specific information. In this file, you would initialize
all application specific variables to their default values.
Step 4) Now, it's time to add a Web Form file to the project. This is the file which will contain all
the web-specific code for our project.

 Right-click on the DemoApplication project and

 Choose Add->Web Form from the context menu.

Step 5) In the next screen we are going to be prompted to provide a name for the web form.
1. Give a name for the Web Form. In our case, we are giving it a name of Demo.
2. Click the Ok button.

Automatically Visual Studio will create the Demo Web Form and will open it in Visual Studio.
Step 6) The next step is to add the code, which will do the work of displaying "Hello World." This
can be done by just adding one line of code to the Demo.aspx file.

HTML Code
<html xmlns="www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%Response. Write( "HeIIo World") %>
</div>
</form>
</body>
</html>
Code Explanation:-

 The Response object in ASP.Net is used to send information back to the user. So in our case,
we are using the method "Write" of the Response object to write the text "Hello World." The
<% and %> markers are used to add ASP.net specific code.
If you follow all of the above steps and run your program in Visual Studio, you will get the
follo
win
g
outp
ut.
2. ASP.NET Controls: CheckBox, RadioButton, ListBox, Textbox, Label
ASP.Net has the ability to add controls to a form such as textboxes and labels.
Let's look at the other controls available for Web forms and see some of their common properties.
In our example, we will create one form which will have the following functionality.
1. The ability for the user to enter his name.
2. An option to choose the city in which the user resides in
3. The ability for the user to enter an option for the gender.
4. An option to choose a course which the user wants to learn. There will be choices for both
C# and ASP.Net
Let's look at each control in detail. Let's add them to build the form with the above-mentioned
functionality.
Step 1) The first step is to open the Forms Designer for the Demo web form. Once you do this, you
will be able to drag controls from the toolbox to the Web form.
To open the Designer web form,

 Right-click the Demo.aspx file in the Solution Explorer and


 Choose the menu option View Designer.

Once you perform the above step, you will be able to see your Form Designer as shown below.
Step 2) The next step is to drag the 'label' control on to the Web Form from the toolbox as shown
below.

Step 3) Once the label has been added, follow the following steps.
1. Go to the properties window by right-clicking on the label control
2. Choose the Properties menu option

Step 4) From the properties window, change the name of the Text property to Name
Similarly, also change the ID property value of the control to lblName. By specifying a meaningful
ID to controls, it becomes easier to access them during the coding phase. This is shown below.

Output :
Similarly we can insert other controls like textbox, checkbox, radio button, listbox, butons etc. Into
our form. The
final web page is
shown in the
browser as
follows -

Event Handler in ASP.Net


When working with a web form, you can add events to controls. An event is something that
happens when an action is performed. Probably the most common action is the clicking of a button
on a form.
In web forms, you can add code to the corresponding aspx.cd file. This code can be used to perform
certain actions when a button is pressed on the form. This is generally the most common event in
Web Forms. Let's see how we can achieve this.
We are going to make this simple. Just add an event to the button control to display the name which
was entered by the user. Let's follow the below steps to achieve this.
Step 1) First you have to double-click the Button on the Web Form. This will bring up the event

code for the button in Visual Studio.

The btnSubmit_Click event is automatically added by Visual Studio when you double click the
button in the web forms designer.
Step 2) Let's now add code to the submit event to display the name textbox value and the location

chosen by the user.

Code :
protected void btnSubmit_Click(object sender,EventArgs e)
{
Response.Write(txtName.Text + "</br>");
Response.Write(lstLocation.SelectedItem.Text + "</br>");
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
Code Explanation:-
1. The above line of code does the simplest thing. It takes the value of the Name textbox
control and sends it to the client via the Response object. So if you want to enter the string
"Guru99" in the name text box, the value of txtName. A text would be 'Guru99'.
2. The next line of code takes the selected value of the listbox via the property
'lstLocation.SelectedItem.text'. It then writes this value via the Response.Write method back
to the client.
3. Finally, we make all the controls on the form as invisible. If we don't do this, all the controls
plus our response values will be displayed together.
Normally, when a person enters all the information on the form such as the Name, location,
Gender, etc. The next page shown to the user should only have the information which was
not entered. The user does not want to see the Name, Gender, location controls again. But
ASP.Net does not know this, and hence, by default, it will again show all the controls when
the user clicks the Submit button. Hence, we need to write code to ensure all the controls are
hidden so that the user just sees the desired output.
One you make the above changes, you will see the following output
In the Output screen, carry out the following steps
1. Give a name of Guru99 in the name textbox
2. Choose a location in the listbox of Bangalore
3. Click on the Submit button

3. ASP.NET Session Management


The HTTP protocol on which all web applications work is a stateless protocol. By stateless, it just
means that information is not retained from one request to another.
For instance, if you had a login page which has 2 textboxes, one for the name and the other for the
password. When you click the Login button on that page, the application needs to ensure that the
username and password get passed onto the next page.
Session management is a way in ASP.net to ensure that information is passed over from one page to
the other.

 The view state property of a page is used to automatically pass the information of controls
from one page to the other.

 The 'Session' object is used to store and retrieve specific values within a web page.

protected void btnSubmit_Click(object sender,EventArgs e)


{
Session["Name"] = txtName.Text;
Response.Write(Session["Name"]);
lblName.Visible = false;
txtName.Visible = false;
1stLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;

btnSubmit.Visible
= false;
}
4. ASP.NET Web Forms: User Controls
Step 1) The first step is to create a web user control and add it to our Visual Studio Solution.

 Go to the Solution Explorer in Visual Studio and right click the DemoApplication Solution.

 Choose the menu item Add->New Item


Step 2) In the next step, we need to choose the option of creating a web user control.
1) In the project dialog box, we can see various options for creating different types of
components. Click the "Web" option on the left-hand side.
2) When we click the "Web" option, you see an option for "Web Forms User control." Click
this option.
3) We then give a name for the Web Control "Guru99Control".
4) Finally, click the 'Add' button to let Visual Studio add the web user control to our solution.
Step 3) Now it's time to add the custom code to the Web user control. Our code will be based on
pure HTML syntax. Add the following code to the 'Guru99Control.ascx' file

Registering User Controls on a ASP.NET web forms


Once the custom 'control' is created, we need to use it in our web application. The first step is to
register the component in our application (Demo.aspx). This is the pre-requisite to use in any
custom web control in an ASP.Net application.
First, we will register our custom 'control' into the Demo.aspx file.
Step 1) Ensure that you are working on the demo.aspx file. It is in this file that the web user control
will be registered. This can be done by double-clicking the demo.aspx file in the Solution explorer
of your .Net solution.
The default code consists of steps, which are required to ensure that the form can run as an ASP.Net
web form in the browser.

Step 2) Now let's add our code to register the user control. The screenshot below shows registration
of the user control to the above basic code.
Output:

5. Fundamentals of Database connectivity


ASP.Net has the ability to work with a majority of databases. The most common being Oracle and
Microsoft SQL Server. But with every database.In our examples, we will look at working with the
Microsoft SQL Server as our database.
While working with databases, the following concepts which are common across all databases.
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.

 Selecting data from the database – Once the connection is established, data is fetched
from the database. ASP.Net 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.
 Inserting data into the database – ASP.Net is used to insert records into the database.
Values for each row that needs to be inserted in the database are specified in ASP.Net.
 Updating data into the database – ASP.Net can also be used to update existing records
into the database. New values can be specified in ASP.Net for each row that needs to be
updated into the database.
 Deleting data from a database – ASP.Net can also be used to delete records from the
database. The code is written to delete a particular row from the database.
ASP.NET Database Connections
we will connect to a database which has the name of Demodb. The credentials used to connect to
the database are given below

 Username – sa

 Password – demo123
Step 1) Let's first ensure that you have your web application (DemoApplication) opened in Visual
Studio. Double click the 'demo.aspx.cs' 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.

Output:
(a) ASP.NET Read Database using SqlDataReader
To show data accessed using Asp.Net, 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 ASP.Net

Step 1) Let's split the code into two parts,

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

(b) Insert Database Record using InsertCommand


Just like Accessing data, ASP.Net has the ability to insert records into the database as well. Let's
take the same table structure used for inserting records.

TutorialID TutorialName
1 C#
2 ASP.Net

Let's change the code in our form, so that we can insert the following row into the table

TutorialID TutorialName
3 VB.Net

Step 1) As the first step let's add the following code to our program. The below code snippet will be
used to insert an existing record in our database.

namespace DemoApplication
{
public partial class Demo System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql="";

sql = "Insert into demotb(TutorialID,TutorialName) value(3, '" +


"VB.Net +"')";

command = new SqlCommand(sql,cnn);


adapter.InsertCommand = new SqlCommand(sql,cnn);
adapter.InsertCommand.ExecuteNonQuery();

command.Dispose():
cnn.Close();

}
}
}

Code Explanation:-
1. The first step is to create the following variables
1. SQLCommand – This data type is used to define objects. These objects perform SQL
operations against a database. This object will hold the SQL command which will
run against our SQL Server database.
2. The DataAdapter object is used to perform insert, delete and update SQL commands
3. We then define a string variable, which is "SQL" to hold our SQL command string.
2. The next step is actually to define the SQL statement, which will be used against our
database. In our case, we are issuing an insert statement. This will insert the record of
TutorialID=1 and TutorialName=VB.Net
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. In our data adapter command,

 Associate the insert SQL command to the adapter.


 Then issue the 'ExecuteNonQuery' method. This is used to execute the Insert statement
against our database.
 The 'ExecuteNonQuery' method is used in C# to issue any DML statements (insert, delete
and update operation) against the database.
 To issue any table statements in ASP.Net, one need's to use the 'ExecuteNonQuery' method.
5. We finally close all the objects related to our database operation. Remember this is always a
good practice.
Step 2) As a second step, let's add the same code as in the Accessing data section. This is to display
the recent table data in the browser. For that, we will add the below code to the demo.aspx.cs file.

namespace DemoApplication
{
public partial class Demo System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand sqlquery;
SqlDataReader dataReader;
String Output =" ";
sql = "Select TutorialID,TutorialName from demotb";

sqlquery = new SqlCommand(sql, cnn);

dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + "-" +
dataReader.GetValue(1) + "</br>";
}

Response.Write(Output);
dataReader.Close();
command.dispose();
conn.Close();
}
}
}

When the above code is set, and the project is executed in Visual Studio, you will get the below
output.
Output:-

In the browser window, you will see that the rows was successfully inserted in the database.
(C) Update Database Record using UpdateCommand
ASP.Net has the ability to update existing records from a database. Let's take the same table
structure which was used above for the example to insert records.

TutorialID TutorialName
1 C#
2 ASP.Net
3 VB.Net

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 "VB.Net". Which we will update it to "VB.Net complete"
while the row value for Tutorial ID will remain same.
Old row

TutorialID TutorialName
3 VB.Net
New row

TutorialID TutorialName
3 VB.Net complete
Step 1) As the first step let's add the following code to our program. The below code snippet will be
used to update an existing record in our database.

namespace DemoApplication
{
public partial class Demo System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql="";

sql = "Update demotb set TutorialName='"VB.Net Complete"+"'


where TutorialID=3";

command = new SqlCommand(sql,cnn);

adapter.InsertCommand = new SqlCommand(sql,cnn);


adapter.InsertCommand.ExecuteNonQuery;

command.Dispose():
cnn.Close();

}
}
}

Code Explanation:-
1. The first step is to create the following variables
1. SQLCommand – his data type is used to define objects to perform SQL operations
against a database. This object will hold the SQL command which will run against
our SQL Server database.
2. The dataadapter object is used to perform insert, delete and update SQL commands
3. We then define a string variable, which is SQL to hold our SQL command string.
2. The next step is actually to define the SQL statement which will be used against our
database. In our case, we are issuing an 'update' statement. This will update the Tutorial
name to "VB.Net Complete". The TutorialID will remain unchanged, and the value will be
3.
3. Next, we will create the command object. This is used to execute the SQL statement against
the database. In the SQL command, you have passed the connection object and the SQL
string
4. In our data adapter command, we now associate the insert SQL command to our adapter. We
then issue the ExecuteNonQuery method. This is used to execute the Update statement
against our database.
5. We finally close all the objects related to our database operation. Remember this is always a
good practice.
Step 2) As a second step, let's add the same code as in the Accessing data section. This is to display
the recent table data in the browser. For that, we will add the below code

namespace DemoApplication
{
public partial class Demo System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand sqlquery;
SqlDataReader dataReader;
String Output =" ";
sql = "Select TutorialID,TutorialName from demotb";

sqlquery = new SqlCommand(sql, cnn);

dataReader = command.ExecuteReader();

while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + "-" +
dataReader.GetValue(1) + "</br>";
}

Response.Write(Output);
dataReader.Close();
command.dispose();
conn.Close();
}
}
}

When the above code is set, and the project is executed using Visual Studio, you will get the below
output.
Output:-

In the browser window, you will see that the rows were successfully updated in the database.
(D) Delete Database Record using DeleteCommand
ASP.Net can delete existing records from a database. Let's take the same table structure which was
used above for the example to delete records.

TutorialID TutorialName

1 C#

2 ASP.Net

3 VB.Net complete

Let's change the code in our form so that we can delete the following row
TutorialID TutorialName

3 VB.Net 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.
Step 1) As the first step let's add the following code to our program. The below code snippet will be
used to delete an existing record in our database.

namespace DemoApplication
{
public partial class Demo System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql="";

sql = "Delete demotb where TutorialID=3";

command = new SqlCommand(sql,cnn);

adapter.InsertCommand = new SqlCommand(sql,cnn);


adapter.InsertCommand.ExecuteNonQuery;

command.Dispose():
cnn.Close();

}
}
}

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 issue the 'ExecuteNonQuery' method which is used to execute the delete statement
against our database.
Step 2) As a second step, let's add the same code as in the Accessing data section. This is to display
the recent table data in the browser. For that, we will add the below code.

namespace DemoApplication
{
public partial class Demo System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand sqlquery;
SqlDataReader dataReader;
String Output ="";
sql = "Select TutorialID,TutorialName from demotb";

sqlquery = new SqlCommand(sql, cnn);

dataReader = command.ExecuteReader();

while(dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + "-" +
dataReader.GetValue(1) + "</br>";
}

Response.Write(Output);
dataReader.Close();
command.dispose();
conn.Close();
}
}
}

When the above code is set, and the project is executed using Visual Studio, you will get the below
output.
Output:-
(E) Connecting Asp.net Controls to Data
We have seen how we can use ASP.Net commands such as SQLCommand and SQLReader to fetch
data from a database. We also saw how we can read each row of the table display it on the web
page.
There are methods available to link controls directly to different fields in the table. At the moment,
only the below controls can be bound to an ASP.Net application
1. CheckboxList
2. RadioButtonList
3. DropDownlist
4. Listbox
So let's see an example of how we can use control binding in ASP.Net. Here we will take a listbox
example. Let's say we have the following data in our database.

TutorialID TutorialName

1 C#

2 ASP.Net

3 VB.Net complete

Let's use the Listbox control and see how it can automatically pick up the data from our Demotb
table.
Let's follow the below-mentioned steps to achieve this.
Step 1) Construct the basic web form. From the toolbox in Visual Studio, drag and drop 2
components- labels and Listboxes. Then carry out the following substeps;
1. Put the text value of the first label as TutorialID
2. Put the text value of the second label as TutorialName
Below is how the form would look like once the above-mentioned steps are performed.

Step 2) The next step is to start connecting each listbox to the database table.
1. First, click on the Listbox for Tutorial ID. This will bring up another dialog box to the side
of the control.
2. From the dialog box, we need to click on the option of Choose Data source.
Step 3) You will then be presented with a dialog box. This can be used to create a new data source.
The data source will represent a connection to the database. Choose the option of 'New data source'.

Step 4) The below screen will be prompted after choosing the new data source in the last step. Here
we need to mention the type of data source we want to create.
1. Choose the database option to work with an SQL Server database.
2. Now we need to give a name to our data source. Here we are giving it a name of
DemoDataSource.
3. Finally, we click the 'OK' button to proceed to the next screen.

Step 5) Now we need to create a connection to our database. In the next screen, click on the New
Connection button
Step 6) Next you need to add the credentials to connect to the database.
1. Choose the server name on which the SQL Server resides
2. Enter the user id and password to connect to the database
3. Choose the database as 'demotb'
4. Click the 'OK' button.

Step 7) On the next screen, you will be able to see the Demotb table. Just click on the Next button
to accept the default setting.
Step 8) You will now be able to test the connection on the next screen.
1. Click on the Test Query button to just see if you are able to get the values from the table
2. Click the Finish button to complete the wizard.

Step 9) Now on the final screen, you can click the 'OK' button. This will now bind the TutorialID
listbox to the TutorialID field name in the 'demotb' table.

Step 10) Now it's time to bind the Tutorial Name listbox to the Tutorial Name field.
1. First, click on the Tutorial Name Listbox.
2. Next, Choose from Data Source in the dialog box which appears at the side of the Listbox.

Step 11) You will already see the DemoDataSource when choosing the Data Source in the next
screen.
1. Choose the DemoData Source
2. Click on the OK button.
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 listboxes display the Tutorial ID and Tutorial Names
respectively

Summary

 ASP.Net can work with databases such as Oracle and Microsoft SQL Server.
 ASP.Net has all the commands which are required to work with databases. This involves
establishing a connection to the database. You can perform operations such as select, update,
insert and delete.
 The datareader object in ASP.Net is used to hold all the data returned by the database. The
While loop in ASP.net can be used to read the data rows one at a time.
 The data adapter object is used to perform SQL operations such as insert, delete, and update.
 ASP.Net can bind controls to the various fields in a table. They are bound by defining a data
source in ASP.Net. The data source is used to pull the data from the database and populate
them in the controls.

You might also like