0% found this document useful (0 votes)
4 views

aspnotes

ASP.NET is a Microsoft web framework for developing websites, web applications, and web services, integrating HTML, CSS, and JavaScript. It includes a page lifecycle with various stages such as initialization, loading, and rendering, and features like global.asax for application events and web.config for configuration settings. Additionally, it offers various controls like Html and Server controls, Rich controls, and navigation features such as Menu Control and Master Pages for consistent web design.

Uploaded by

sayyed.mht
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

aspnotes

ASP.NET is a Microsoft web framework for developing websites, web applications, and web services, integrating HTML, CSS, and JavaScript. It includes a page lifecycle with various stages such as initialization, loading, and rendering, and features like global.asax for application events and web.config for configuration settings. Additionally, it offers various controls like Html and Server controls, Rich controls, and navigation features such as Menu Control and Master Pages for consistent web design.

Uploaded by

sayyed.mht
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

• What is asp.

net
It is a web framework designed and developed by Microsoft. It is used to
develop websites, web applications and web services. It provides fantastic
integration of HTML, CSS and JavaScript. It was first released in January
2002. It is built on the Common Language Runtime (CLR) and allows
programmers to write code using any supported .NET language.

• ASP.NET Page Lifecycle


In ASP.NET, a web page has execution lifecycle that includes various
phases. These phases include initialization, instantiation, restoring and
maintaining state etc. it is required to understand the page lifecycle so that
we can put custom code at any stage to perform our business logic.

• Page Lifecycle stages


The following table contains the lifecycle stages of ASP.NET web page.

Stage Description

Page This stage occurs before the


request lifecycle begins. When a page is
requested by the user, ASP.NET
parses and compiles that page.

Start In this stage, page properties


such as Request and response
are set. It also determines the
Request type.

Initialization In this stage, each control's


UniqueID property is set. Master
page is applied to the page.

Load During this phase, if page request


is postback, control properties
are loaded with information.
Postback In this stage, event handler is
event called if page request is
handling postback. After that, the Validate
method of all validator controls is
called.

Rendering Before rendering, view state is


saved for the page and all
controls. During the rendering
stage, the page calls the Render
method for each control,
providing a text writer that writes
its output to the OutputStream
object of the page's Response
property.

Unload At this stage the requested page


has been fully rendered and is
ready to terminate.at this stage all
properties are unloaded and
cleanup is performed.

• IIS –
IIS is a protocol server which is used to host a website on server. IIS
stands for Internet Information services.

What is global.asax :
Global.asax is an optional file which is used to handling higher level
application events such as Application_Start, Application_End,
Session_Start, Session_End etc. It is also popularly known as ASP.NET
Application File. This file resides in the root directory of an ASP.NET-based
application.

What is the web.config file :


web.config file is an XML-based configuration file used in ASP.NET-based
applications to manage various settings that are concerned with the
configuration of our website. In this way, we can separate our application
logic from configuration logic. And the main benefit of this is, if we want to
change some configuration settings then we do not need to restart our
application to apply new changes, ASP.NET automatically detects the
changes and applies them to the running ASP.NET application.
The ASP.NET framework uses a hierarchical configuration system. You
can place a web.config file in any subdirectory of an application. The file
then applies to any pages located in the same directory or any
subdirectories.

2. Html and Server Controls and Rich Control


• Html Controls-(Label, TextBox, Button, CheckBox, RadioButton) & Server
controls-(Label,TextBox, Button, CheckBox, RadioButton)
1. Label -

This control is used to display textual information on the web forms. It is


mainly used to create caption for the other controls like: textbox.

To create label either we can write code or use the drag and drop facility of
visual studio 2017.

This is server side control, asp provides own tag to create label. The example
is given below.

< asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>

• This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut


for the label.

TabIndex The tab order of the control.

BackColor It is used to set background color


of the label.
BorderColor It is used to set border color of the
label.

BorderWidth It is used to set width of border of


the label.

Font It is used to set font for the label


text.

ForeColor It is used to set color of the label


text.

Text It is used to set text to be shown


for the label.

ToolTip It displays the text when mouse is


over the label.

Visible To set visibility of control on the


form.

Height It is used to set height of the


control.

Width It is used to set width of the


control.

2. TextBox -
This is an input control which is used to take user input. To
create TextBox either we can write code or use the drag and drop facility of
visual studio IDE.

This is server side control, asp provides own tag to create it. The example is
given below.

< asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>

Server renders it as the HTML control and produces the following code to
the browser.
<input name="TextBox1" id="TextBox1" type="text">

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut


for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color


of the control.

BorderColor It is used to set border color of the


control.

BorderWidth It is used to set width of border of


the control.

Font It is used to set font for the control


text.

ForeColor It is used to set color of the control


text.

Text It is used to set text to be shown


for the control.

ToolTip It displays the text when mouse is


over the control.

Visible To set visibility of control on the


form.

Height It is used to set height of the


control.

Width It is used to set width of the


control.
MaxLength It is used to set maximum number
of characters that can be entered.

Readonly It is used to make control


readonly.

3. Button -
This control is used to perform events. It is also used to submit client request
to the server. To create Button either we can write code or use the drag and
drop facility of visual studio IDE.

This is a server side control and asp provides own tag to create it. The
example is given below.

< asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle=


"Solid" ToolTip="Submit"/>

Server renders it as the HTML control and produces the following code to
the browser.

<input name="Button1" value="Submit" id="Button1" title="Submit" st


yle="border-style:Solid;" type="submit">

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut


for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color


of the control.
BorderColor It is used to set border color of the
control.

BorderWidth It is used to set width of border of


the control.

Font It is used to set font for the control


text.

ForeColor It is used to set color of the control


text.

Text It is used to set text to be shown


for the control.

ToolTip It displays the text when mouse is


over the control.

Visible To set visibility of control on the


form.

Height It is used to set height of the


control.

Width It is used to set width of the


control.

4. CheckBox -
It is used to get multiple inputs from the user. It allows user to select choices
from the set of choices.

It takes user input in yes or no format. It is useful when we want multiple


choices from the user.

To create CheckBox we can drag it from the toolbox in visual studio.

This is a server side control and ASP.NET provides own tag to create it. The
example is given below.
<asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>
Server renders it as the HTML control and produces the following code to
the browser.

< input id="CheckBox2" type="checkbox" name="CheckBox2" /><lab


el for="CheckBox2">J2EE</label>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut


for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color


of the control.

BorderColor It is used to set border color of the


control.

BorderWidth It is used to set width of border of


the control.

Font It is used to set font for the control


text.

ForeColor It is used to set color of the control


text.

Text It is used to set text to be shown


for the control.

ToolTip It displays the text when mouse is


over the control.

Visible To set visibility of control on the


form.
Height It is used to set height of the
control.

Width It is used to set width of the


control.

Checked It is used to set check state of the


control either true or false.

5. RadioButton -
It is an input control which is used to takes input from the user. It allows user
to select a choice from the group of choices.

To create RadioButton we can drag it from the toolbox of visual studio.

This is a server side control and ASP.NET provides own tag to create it. The
example is given below.

< asp:RadioButtonID="RadioButton1" runat="server" Text="Male" Gr


oupName="gender"/>

Server renders it as the HTML control and produces the following code to
the browser.

<input id="RadioButton1" type="radio" name="gender" value="Radio


Button1" /><labelforlabelfor="RadioButton1">Male</label>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut


for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color


of the control.
BorderColor It is used to set border color of the
control.

BorderWidth It is used to set width of border of


the control.

Font It is used to set font for the control


text.

ForeColor It is used to set color of the control


text.

Text It is used to set text to be shown


for the control.

ToolTip It displays the text when mouse is


over the control.

Visible To set visibility of control on the


form.

Height It is used to set height of the


control.

Width It is used to set width of the


control.

GroupName It is used to set name of the radio


button group.

• Rich controls-(DropDownList, Calender) :


1) Calendar -
It is used to display selectable date in a calendar. It also shows data
associated with specific date. This control displays a calendar through which
users can move to any day in any year.

We can also set Selected Date property that shows specified date in the
calendar.
To create Calendar we can drag it from the toolbox of visual studio.

This is a server side control and ASP.NET provides own tag to create it. The
example is given below.

< asp:CalendarID="Calendar1" runat="server" SelectedDate="2017-


06-15" ></asp:Calendar>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard


shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background


color of the control.

BorderColor It is used to set border color of


the control.

BorderWidth It is used to set width of


border of the control.

Font It is used to set font for the


control text.

ForeColor It is used to set color of the


control text.

Text It is used to set text to be


shown for the control.

ToolTip It displays the text when


mouse is over the control.

Visible To set visibility of control on


the form.
Height It is used to set height of the
control.

Width It is used to set width of the


control.

NextMonth Text It is used to set text for the


next month button.

TitleFormat It sets format for month title in


header.

DayHeaderStyle It is used to set style for the


day header row.

DayStyle It is used to apply style to


days.

NextPrevStyle It is used to apply style to the


month navigation buttons.

2) DropDownList -
The DropDownList is a web server control which is used to create an HTML
Select component. It allows us to select an option from the dropdown list. It
can contain any number of items

ASP.NET provides a tag to create DropDownList for web application. The


following is the Syntax of DropDownList tag.

<asp:DropDownList id="DropDownList1" runat="server" >


<asp:ListItem value="value" selected="True|False">
<asp:ListItem>New Delhi </asp:ListItem>
<asp:ListItem>Greater Noida</asp:ListItem>
<asp:ListItem>NewYork</asp:ListItem>
<asp:ListItem>Paris</asp:ListItem>
<asp:ListItem>London</asp:ListItem>
</asp:ListItem>
</asp:DropDownList>

UNIT II NAVIGATION AND VALIDATION CONTROL


3. Navigation Control and Master Page

• Menu Control-

Asp.net Menu Control feature provides a consistent way for your website
users to navigate your website. If you want to use navigation menu control
on your website, then follow these easy steps.

You can add Menu control to your .master page by simply drag and drop
from ToolBox > Navigation > Menu or add the following few lines of code
snippet.

<asp:Menu ID="Menu1" runat="server" RenderingMode="List">


<Items> <asp:MenuItem Text="Home" Value="Home" />
<asp:MenuItem Text="About" Value="About" />
</Items>
</asp:Menu>

• Master Page –

Master pages in ASP.NET work as a template page. All aspx pages


can refer master pages. With the help of Master pages we can define
the look and feel of all the pages in our web site in a single location. If
we have done changes in master page, then the changes will reflect
in all the web pages that refer to master pages.

ASP.NET web page that uses master page for common UI, is called
as content page. Content pages merge with the master pages at
compile time to produce final output. The final page combines the
layout of the master page with the content from the content page.
Before Master pages feature in ASP.NET, developers created
consistent web pages by using custom controls, CSS and JavaScript.
Now developing consistent web pages are very easy with the help of
Master pages. You can dynamically change the common UI part on
master page from content pages.

A master page has the extension .master that can comprise static
text, HTML elements, and server controls. A master page is similar to
an ASP.NET page but it contains @Master directive at the top and
one or more ContentPlaceHolder server controls.
Master page inherits from the MasterPage class.
ContentPlaceHolder is an important control that is related with master
page.
ContentPlaceHolder control is available only on master page. You
can use more than one ContentPlaceHolder control in master page.
ContentPlaceHolder control is used on master page to customize or
add some controls on the content page as follows:

<asp:ContentPlaceHolder ID=”ContentPlaceHolder1” runat=”server”>


</ContenPlaceHolder>

The page-specific content is then put inside a Content control that


points to the relevant ContentPlaceHolder:
<asp:Content ID="Content2"
ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

4. Validation controls

ASP.NET Validation
In this chapter, we will discuss about the data validation in the Web Forms. To perform
validation, ASP.NET provides controls that automatically check user input and require no
code. We can also create custom validation for our application.

ASP.NET validation controls


Following are the validation controls

Validator Description

CompareValidator It is used to compare the


value of an input control
against a value of another
input control.

RangeValidator It evaluates the value of an


input control to check the
specified range.

RegularExpressionValidator It evaluates the value of an


input control to determine
whether it matches a
pattern defined by a
regular expression.
RequiredFieldValidator It is used to make a control
required.

ValidationSummary It displays a list of all


validation errors on the
Web page.

ASP.NET CompareValidator Control


This validator evaluates the value of an input control against another input control on the
basis of specified operator.

We can use comparison operators like: less than, equal to, greater than etc.

CompareValidator Properties

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.


Width It is used to set width of the control.

ControlToCompare It takes ID of control to compare with.

ControlToValidate It takes ID of control to validate.

ErrorMessage It is used to display error message when validation failed.

Operator It is used set comparison operator.

ASP.NET RangeValidator Control


This validator evaluates the value of an input control to check that the value lies between
specified ranges.

It allows us to check whether the user input is between a specified upper and lower
boundary. This range can be numbers, alphabetic characters and dates.

Note: if the input control is empty, no validation will be performed.

The ControlToValidateproperty is used to specify the control to validate.


The MinimumValue and MaximumValue properties are used to set minimum and
maximum boundaries for the control.

RangeValidator Properties

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.


BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

ControlToValidate It takes ID of control to validate.

ErrorMessage It is used to display error message when validation failed.

Type It is used to set datatype of the control value.

MaximumValue It is used to set upper boundary of the range.

MinimumValue It is used to set lower boundary of the range.

ASP.NET RegularExpressionValidator Control


This validator is used to validate the value of an input control against the pattern defined
by a regular expression.

It allows us to check and validate predictable sequences of characters like: e-mail address,
telephone number etc.
The ValidationExpression property is used to specify the regular expression, this
expression is used to validate input control.

RegularExpression Properties

Property Description

AccessKey It is used to set keyboard shortcut for the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

ErrorMessage It is used to set error message that display when


validation fails.

ControlToValidate It takes ID of control to validate.

ValidationExpression It is used to set regular expression to determine validity.

ASP.NET RequiredFieldValidator Control


This validator is used to make an input control required. It will throw an error if user leaves
input control empty.

It is used to mandate form control required and restrict the user to provide data.
Note: It removes extra spaces from the beginning and end of the input value before
validation is performed.

The ControlToValidateproperty should be set with the ID of control to validate.

RequiredFieldValidator Properties

Property Description

AccessKey It is used to set keyboard shortcut for the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

ErrorMessage It is used to set error message that display when validation fails.

ControlToValidate It takes ID of control to validate.


UNIT-III STATE MANAGEMENT AND
DATA CONTROL
5. State Management
• ASP.NET Session
In ASP.NET session is a state that is used to store and retrieve values of a
user.

It helps to identify requests from the same browser during a time period
(session). It is used to store value for the particular time session. By default,
ASP.NET session state is enabled for all ASP.NET applications.

Each created session is stored in SessionStateItemCollection object. We


can get current session value by using Session property of Page object.
Let's see an example, how to create an access session in asp.net
application.

if (password.Text=="qwe123")
{
// Storing email to Session variable
Session["email"] = email.Text;
}
// Checking Session variable is not empty
if (Session["email"] != null)
{
// Displaying stored email
Label3.Text = "This email is stored to the session.";
Label4.Text = Session["email"].ToString();
}
• ASP.NET Cookie
ASP.NET Cookie is a small bit of text that is used to store user-specific
information. This information can be read by the web application whenever
user visits the site.
When a user requests for a web page, web server sends not just a page, but
also a cookie containing the date and time. This cookie stores in a folder on
the user's hard disk.

When the user requests for the web page again, browser looks on the hard
drive for the cookie associated with the web page. Browser stores separate
cookie for each different sites user visited.

Note: The Cookie is limited to small size and can be used to store only
4 KB (4096 Bytes) text.

There are two ways to store cookies in ASP.NET application.

o Cookies collection
o HttpCookie

We can add Cookie either to Cookies collection or by creating instance of


HttpCookie class. both work same except that HttpCookie require Cookie
name as part of the constructor.

HttpCookie Example

----------- Creating Cookie --------------------------//


// Creating HttpCookie instance by specifying name "student"
HttpCookie cokie = new HttpCookie("student");
// Assigning value to the created cookie
cokie.Value = "Rahul Kumar";
// Adding Cookie to the response instance
Response.Cookies.Add(cokie);
//--------------- Fetching Cookie -------------------------//
var co_val = Response.Cookies["student"].Value;
Label1.Text = co_val;
• View State

View State is the method to preserve the Value of the Page and Controls
between round trips. It is a Page-Level State Management technique. View
State is turned on by default and normally serializes the data in every
control on the page regardless of whether it is actually used during a post-
back.
Features Of View State

These are the main features of view state,


1. Retains the value of the Control after post-back without using a
session.
2. Stores the value of Pages and Control Properties defined in the
page.
3. Creates a custom View State Provider that lets you store View
State Information in a SQL Server Database or in another data
store.
Advantages of View State
1. Easy to Implement.
2. No server resources are required: The View State is contained in
a structure within the page load.
3. Enhanced security features: It can be encoded and compressed
or Unicode implementation.
Disadvantages of View State
1. Security Risk: The Information of View State can be seen in the
page output source directly. You can manually encrypt and
decrypt the contents of a Hidden Field, but It requires extra
coding. If security is a concern then consider using a Server-
Based state Mechanism so that no sensitive information is sent
to the client.
2. Performance: Performance is not good if we use a large amount
of data because View State is stored in the page itself and
storing a large value can cause the page to be slow.
3. Device limitation: Mobile Devices might not have the memory
capacity to store a large amount of View State data.
4. It can store values for the same page only.
When We Should Use View State
1. When the data to be stored is small.
2. Try to avoid secure data.
How to Enable and Disable View State

You can enable and disable View State for a single control as well as at the
page level also. To turn off View State for a single control, set the
EnableViewState property of that control to false.

TextBox1.EnableViewState=false;
To turn off the View State for an entire page, we need to
set EnableViewState to false of the page directive as shown below:

<%Page Language="C#" EnableViewState="false";


• ASP.NET QueryString

A query string is a collection of characters input to a computer or web


browser. A Query String is helpful when we want to transfer a value from
one page to another. When we need to pass content between the HTML
pages or aspx Web Forms in the context of ASP.NET, a Query String is
very easy to use and the Query String follows a separating character,
usually a Question Mark (?). It is basically used for identifying data
appearing after this separating symbol. A Query String Collection is used to
retrieve the variable values in the HTTP query string. If we want to transfer
a large amount of data then we can't use the Request.QueryString. Query
Strings are also generated by form submission or can be used by a user
typing a query into the address bar of the browsers. Query Strings are
contained in request headers. A Query String collection is a parsed version
of the QUERY_STRING variable in the Server Variables collection. It
enable us to retrieve the QUERY_STRING variable by name. When we use
parameters with Request.QueryString, the server parses the parameters
sent to the request and returns the effective or specified data.

Syntax of Query String

Request.QueryString(variable)[(index).count].

protected void Button1_Click(object sender, EventArgs e)


{
Response.Redirect("default2.aspx ?firstname=" + TextBox1.Text + "&las
tname=" + TextBox2.Text);
}

In the second web form we take the one lable for displaying the
values of the first page. For receiving the value from the first page we
write the following code on the page_load of the second page.

protected void Page_Load(object sender, EventArgs e)


{
string firstname = Request.QueryString["firstname"];
string lastname = Request.QueryString["lastname"];
Label1.Text = "welcome" + firstname + " " + lastname;
}

Query String is a group of keywords that send request to the web


server. These requests are used to pass information (parameters) from
one page to another and you can access those information in receiving
page.

This method many browsers supports only 255 character length of url in
query string. The value passed will be visible so some time it cause
security issue.
For send information to other page Response.Redirect() method used and
for retrieve information from url use Request.QueryString() method used.

Query String method we can sent value to only desired page, and value
will be temporarily. So Query string increase the overall performance of
web application.

Points to remember:
?:- Seperator
&:- to seperate two different fileds
----
%, + is used for space management(between the values)

Creating QueryString:-
Responce.Redirect():-

.Redirect("default1.aspx?firstName=Riyaj");

.Redirect("default1.aspx?firstName="+txtUname.text);

.Redirect("default1.aspx?firstName=Riyaj shahu
college&lname=Shaikh");

.Redirect("default1.aspx?firstName="+txtUname.text+"&lname="+txtlname
.text);

Information Retrive from QueryString:


Request.QueryString:-

string s1 = Request.QueryString["firstName"].toString();
string s2 = Request.QueryString["lname"].toString();

Differences between ViewState and SessionState:


ViewState SessionState

Maintained at page level only. Maintained at session level.


ViewState SessionState

View state can only be visible from Session state value availability is
a single page and not multiple across all pages available in a
pages. user session.

In session state, user data


remains in the server. Data is
available to user until the browser
It will retain values in the event of is closed or there is session
a postback operation occurring. expiration.

Information is stored on the Information is stored on the


client’s end only. server.

used to allow the persistence of used for the persistence of user-


page-instance-specific data. specific data on the server’s end.

SessionState can be cleared by


ViewState values are lost/cleared programmer or user or in case of
when new page is loaded. timeouts.
Usage:
• SessionState: It can be used to store information that you wish
to access on different web pages.
• ViewState It can be used to store information that you wish to
access from same web page.

Cookie- It is a small file that contains user information. It is used to


store information about the user. It is stored in the local computer
browser session. It contains site specific information that the server
sends to the client it can be temporary with expiry date or
persistent.

The purpose of a cookie is to store information about a particular


client, session or application cookie is saved on the client device. We
can access cookie information by requesting from the browser, client
sends the information in the cookie along with the request
information.

6. Data Controls
➢ The Grid View : Automatically Generating Columns, Defining
Columns-

When the Auto Generate Columns property is set to true, an Auto


Generated Field object is automatically created for each field in the data
source. Each field is then displayed as a column in the Grid View control in
the order that the fields appear in the data source. This option provides a
convenient way to display every field in the data source; however, you have
limited control of how an automatically generated column field is displayed
or behaves.

Instead of letting the Grid View control automatically generate the column
fields, you can manually define the column fields by setting the Auto
Generate Columns property to false and then creating a
custom Columns collection. In addition to bound column fields, you can
also display a button column field, a check box column field, a command
field, a hyperlink column field, an image field, or a column field based on
your own custom-defined template.

Code:-
ASPX Coding –

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="studentRec.aspx.cs" Inherits="studentRec" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="lblSid" runat="server" Text="Student
ID"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtStudID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblSname" runat="server" Text="Student
Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtStudName"
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblSClass" runat="server" Text="Student
ID"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtsclass" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnAdd" runat="server" Text="Add Student1"
onclick="btnAdd_Click" />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" PageSize="20">
</asp:GridView>
</div>
</form>
</body>
</html>

ASPX.CS coding
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

public partial class studentRec : System.Web.UI.Page

SqlConnection conn;

SqlCommand cmd;

SqlDataAdapter da

; DataTable dt;

protected void Page_Load(object sender, EventArgs e)


{

conn = new
SqlConnection(@"DataSource=DESKTOP24CMRE4\SQLEXPRESS;

Initial Catalog=RsmlStudent;Integrated Security=True"); //conn.Open();


FillDataGrid();

protected void btnAdd_Click(object sender, EventArgs e)

string qry; qry = "insert into studdtl values(" + txtStudID.Text + ",'" +


txtStudName.Text + "','" + txtsclass.Text + "')";

//qry = "update studdtl set StudName = '" + txtStudName.Text + "' where


studID = " + txtStudID.Text; conn.Open();

cmd = new SqlCommand();

cmd.Connection = conn; cmd.CommandText = qry;


cmd.ExecuteNonQuery();

conn.Close();

Response.Write("Redocrd Saved....");

FillDataGrid();

private void FillDataGrid()

conn.Open();

da = new SqlDataAdapter("select * from studdtl", conn);

dt = new DataTable();
da.Fill(dt);

GridView1.DataSource = dt;

GridView1.DataBind();

conn.Close();

protected void GridView1_Sorting(object sender, GridViewSortEventArgs


e)

DataTable dt = GridView1.DataSource as DataTable;

if (dt != null)

DataView sortData = new DataView(dt);

sortData.Sort = e.SortExpression + " " + ascdec(e.SortDirection);

GridView1.DataSource = sortData;

GridView1.DataBind();

private string ascdec(SortDirection sortAcsDec)

string newSortType;

if (sortAcsDec == SortDirection.Ascending)

{
newSortType = "ASC";

else

newSortType = "DESC";

return newSortType;

protected void GridView1_PageIndexChanging(object sender,


GridViewPageEventArgs e)

GridView1.PageIndex = e.NewPageIndex; FillDataGrid();

UNIT-IV WEB SERVICES AND ADO.NET


7. ADO.NET

a. What is ADO.NET?

ADO.NET 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.
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.

b. SqlConnection , SqlCommand

SqlConnection and SqlCommand are classes of a connected


architecture and found in the System.Data.SqlClient namespace. The
SqlConnection class makes a connection with the database. Further,
this connection (database connection) is used by the SqlCommand to
work with that database. The SqlCommand class is used to execute the
SQL statements. Let's work with the SqlConnection and SqlCommand
classes with simple examples.

Open() : The open() method is used to open the Database connection.


Close() : The close() method is used to close the Database connection.

Code :

1. using System;
2. using System.Data;
3. using System.Data.SqlClient;
4.
5. namespace sqlconnectionANDsqlcommand
6. {
7. public partial class Form1 : Form
8. {
9. public Form1()
10. {
11. InitializeComponent();
12. }
13. private void btnclick_Click(object sender,
EventArgs e)
14. {
15. SqlConnection conn = new SqlConnection(
"Database=student;Server=.;user=sa;password=aaaaaaa"
);
16. conn.Open(); // Open the connection
17. // body
18. // body
19. conn.Close(); // Close the connection
20. }
21. }
22. }
SqlCommand Class

The main role of SqlCommand is to execute SQL statements.

SqlCommand Properties

CommandText: The commandText property is used to set the SQL


statement.

Connection: This property is used to get connection to the database


source which is specified in SqlConnection.

SqlCommand Method

ExecuteNonQuery() : The ExecuteNonQuery() method does not return


any record. Which means we use ExecuteNonQuery() in all operations
with databases except retrieving records from a database. It only
returns the number of affected rows.

Now we use this method in our application. There is a database


"student" and a database "student_detail" which has no record. I am
giving a simple example to insert a record into database.

1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Linq;
7. using System.Text;
8. using System.Windows.Forms;
9. using System.Data.SqlClient;
10.
11. namespace sqlconnectionANDsqlcommand
12. {
13. public partial class Form1 : Form
14. {
15. public Form1()
16. {
17. InitializeComponent();
18. }
19. private void Form1_Load(object sender, Even
tArgs e)
20. {
21. }
22.
23. private void btnclick_Click(object sender,
EventArgs e)
24. {
25. // Creating instance of SqlConnection
26. SqlConnection conn = new SqlConnection(
"Database=student;Server=.;user=sa;password=aaaaaaa"
);
27. conn.Open();// open the database connec
tion
28. SqlCommand cmd = new SqlCommand();// Cr
eating instance of SqlCommand
29. cmd.Connection = conn; // set the conne
ction to instance of SqlCommand
30. cmd.CommandText = "insert into student_
detail values (" + txtrollno.Text + ",'" + txtname.T
ext + "','" + txtcourse.Text + "')"; // set
31. //the sql command ( Statement )
32. cmd.ExecuteNonQuery();
33. MessageBox.Show("Record Saved"); // sho
wing messagebox for confirmation message for user
34. conn.Close();// Close the connection
35. }
36.
37. }
38. }

DataSet

DataSet is a disconnected orient architecture that means there is no


need of active connections during work with datasets and it is a
collection of DataTables and relations between tables. It is used to hold
multiple tables with data. You can select data form tables, create views
based on table and ask child rows over relations. Also DataSet provides
you with rich features like saving data as XML and loading XML data.

protected void BindGridview() {


SqlConnection conn = new SqlConnection("Data
Source=abc;Integrated Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

DataAdapter

DataAdapter will acts as a Bridge between DataSet and database. This


dataadapter object is used to read the data from database and bind
that data to dataset. Dataadapter is a disconnected oriented
architecture. Check below sample code to see how to use DataAdapter
in code:

protected void BindGridview() {


SqlConnection con = new SqlConnection("Data
Source=abc;Integrated Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

• Lets you close the connection as soon it's done loading data,
and may even close it for you automatically
• All of the results are available in memory
• You can iterate over it as many times as you need, or even
look up a specific record by index
• Has some built-in faculties for updating back to the database.
Simple Application using ADO.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="


WebFormAdoNet.aspx.cs"
Inherits="ado.netWebFormExample.WebFormAdoNet" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">
<asp:Label runat="server" Text="User Name" ID="user
namelabelId"></asp:Label></td>
<td>

<asp:TextBox ID="UsernameId" runat="server"></asp:TextBox></td>


</tr>
<tr>
<td class="auto-style2">

<asp:Label runat="server" Text="Email ID"></asp:Label></td>


<td>

<asp:TextBox ID="EmailId" runat="server"></asp:TextBox></td>


</tr>
<tr>
<td class="auto-style2">
<asp:Label runat="server" Text="Contact"></asp:Label></td>
<td>

<asp:TextBox ID="ContactId" runat="server"></asp:TextBox></td>


</tr>
<tr>
<td class="auto-style2"></td>
<td>
<asp:Button ID="ButtonId" runat="server" Text="Submit" OnClick="Butto
nId_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
<table class="auto-style1">
<tr>
<td class="auto-style3">
<asp:Label ID="Label2" runat="server"></asp:Label></t>

<td>
<asp:Label ID="Label5" runat="server"></asp:Label></t>

</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="Label3" runat="server"></asp:Label></t>

<td>
<asp:Label ID="Label6" runat="server"></asp:Label></t>

</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="Label4" runat="server"></asp:Label></t>

<td>
<asp:Label ID="Label7" runat="server"></asp:Label></t>

</tr>
</table>
</body>
</html>
CodeBehind

// WebFormAdoNet.aspx.cs

using System;
using System.Data.SqlClient;
namespace ado.netWebFormExample
{
public partial class WebFormAdoNet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonId_Click(object sender, EventArgs e)
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrat
ed security=SSPI");
// Writing insert query
string query = "insert into student(name,email,contact)values('"+Use
rnameId.Text+ "',
'" + EmailId.Text + "','" + ContactId.Text + "')";
SqlCommand sc = new SqlCommand(query,con);
// Opening connection
con.Open();
// Executing query
int status = sc.ExecuteNonQuery();
Label1.Text = "Your record has been saved with the followin
g details!";
// ----------------------- Retrieving Data ------------------ //
SqlCommand cm = new SqlCommand("select top 1 * from
student", con);
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
sdr.Read();
Label2.Text = "User Name"; Label5.Text = sdr["name"].To
String();
Label3.Text = "Email ID"; Label6.Text = sdr["email"].ToStr
ing();
Label4.Text = "Contact"; Label7.Text = sdr["contact"].To
String();
}
catch (Exception ex)
{
Console.WriteLine("OOPs, something went wrong." + ex);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}

You might also like