1 Asp - Net Notes
1 Asp - Net Notes
1 Asp - Net Notes
NET
Introduction
ASP.NET is Microsoft’s flagship technology for building highly interactive, highly scalable websites. Some of the largest websites
hosted on the Internet were built with the ASP.NET Framework, including Dell (www.Dell.com), MySpace (www.MySpace.com), and
Microsoft (www.Microsoft.com).
If you are using Visual Web Developer or Visual Studio, you first need to create a new website. Start Visual Web Developer and
select the menu option File, New Web Site.
File class—Enables you to represent a file on your hard drive. You can use the File class to check whether a file exists, create a new
file, delete a file, and perform many other file-related tasks.
Graphics class—Enables you to work with different types of images such as GIF, PNG, BMP, and JPEG images. You can use the
Graphics class to draw rectangles, arcs, ellipsis, and other elements on an image.
Random class—Enables you to generate a random number.
SmtpClient class—Enables you to send email. You can use the SmtpClient class to send emails that contain attachments and HTML
content.
The .NET Framework contains almost 13,000 classes you can use when building applications
Each class in the Framework can include properties, methods, and events. The properties, methods, and events exposed by a class
are the members of a class.
Namespaces
There are almost 13,000 classes in the .NET Framework. This is an overwhelming number. Fortunately, Microsoft divided the
classes in the Framework into separate namespaces. A namespace is simply a category
The first part of the control declaration, the asp: prefix, indicates the namespace for the control. All the standard ASP.NET controls
are contained in the System.Web.UI.
Ex: <asp:TextBox id=”TextBox1” runat=”Server” />
WebControls namespace. The prefix asp: represents this namespace. Next, the declaration contains the name of the control being
declared. In this case, a TextBox control is being declared. This declaration also includes an ID attribute. You use the ID to refer to the
control in the page within your code. Every control must have a unique ID.
The declaration also includes a runat=”Server” attribute. This attribute marks the tag as representing a server-side control.
The next time anyone requests the same page in the future, the page is not compiled again. The previously compiled class is
executed and the results are returned to the browser. If the ASP.NET page is modified in any way, the corresponding .NET class is
automatically deleted. The next time someone requests the page, the Framework automatically compiles the modified page source
into a new .NET class. This process is called dynamic compilation.
void Page_Load()
{
if (!Page.IsPostBack)
TextBox1.Text = “Hello”;
else
TextBox1.Text = “Welcome”;
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Using the Label Control
Whenever you need to modify the text displayed in a page dynamically, you can use the Label control.
The Label control supports several properties you can use to format the text displayed by the Label (this is not a complete list):
BackColor—Enables you to change the background color of the label.
BorderColor—Enables you to set the color of a border rendered around the label.
BorderStyle—Enables you to display a border around the label. Possible values are NotSet, None, Dotted, Dashed, Solid, Double,
Groove, Ridge, Inset, and Outset.
BorderWidth—Enables you to set the size of a border rendered around the label.
CssClass—Enables you to associate a Cascading Style Sheet class with the label.
Font—Enables you to set the label’s font properties.
ForeColor—Enables you to set the color of the content rendered by the label.
Style—Enables you to assign style attributes to the label.
ToolTip—Enables you to set a label’s title attribute.
Text—Enables you to provide a text for a control to display
TextAlign—Enables you to align the label for the check box. Possible values are Left and Right.
ButtonOnClientClick.aspx
Displaying a client-side confirmation dialog box.
OnClick=”btnDelete_Click”
OnClientClick=”return confirm(‘Are you sure?’);”
The page contains a birth date field. If you enter a value that is not a date, then the validation error message is displayed
You can also use the CompareValidator to perform a comparison against a fixed value.
Finally, you can use a CompareValidator to compare the value of one form field against another form field.
The second parameter passed to the ServerValidate event handler is an instance of the ServerValidateEventArgs class. This class has
properties:
Value—Represents the value of the form field being validated.
IsValid—Represents whether validation fails or succeeds.
ValidateEmptyText—Represents whether validation is performed when the form field being validated does not contain a value.
Ex: Contains a timed test. If you don’t answer the question within five seconds, then the CustomValidator control displays a validation
error message
The most important types of files in a Theme folder are the following:
. Skin files
. Cascading Style Sheet files
input
{
background-color:Yellow;
border:double 3px orange;
}
.button
{
background-color:#eeeeee;
}
Global.asax
Every web application created in VS.NET creates a file called 'global.asax' and 2 related files called
'global.asax' and 'global.asax.resx'. The files global.asax is a replacement for the global.asa file used in
classic ASP.
Global.asax.cs is the code behind file for he global.asax. This file is used to handle global events in the web
application.
If a page level event happens, it can be handled in code behind file of the corresponding page. But there are
couple of events which are not specific to any page. These events are applicable to the entire application.
QueryString
Default.aspx
View State
int Counter;
ASP.NET Membership to authenticate users, create new users, and change user properties.
Login—Enables you to display a user login form.
CreateUserWizard—Enables you to display a user registration form.
LoginStatus—Enables you to display either a log in or log out link, depending on a user’s
authentication status.
LoginName—Enables you to display the current user’s registered username.
ChangePassword—Enables you to display a form that allows users to change their passwords.
PasswordRecovery—Enables you to display a form that allows a user to receive an email
containing his or her password.
LoginView—Enables you to display different content to different users depending on the user’s
authentication status or role.
Threads
ASP.NETs pipeline request architecture tries to achieve a balance between the number of
threads executing requests and available resources.
Buffer
Buffering is on by default in ASP.NET.
Garbage Collector
The garbage collector (GC) is a great feature in the CLR that helps performance on the server. A
primary concern for anyone doing server programming is the fragmentation of the heap over a
period of time. With the copy-and-collect type of garbage collection in the CLR, one gets heap
compacting for free. And because the heap is multi-processor aware, with self-tuning capabilities,
its performance tends to be better than self-managed heaps.
In ASP.NET 2.0 the menu can be stored in a file to make it easier to maintain. This file is normally called
web.sitemap, and is stored in the root directory of the web.
Dynamic menus
TreeViews
Site Map Path
The XML file must contain a <siteMap> tag surrounding the content
The <siteMap> tag can only have one <siteMapNode> child node (the "home" page)
Each <siteMapNode> can have several child nodes (web pages)
Each <siteMapNode> has attributes defining page title and URL
Note: The sitemap file must be placed in the root directory of the web and the URL attributes must be
relative to the root directory.
Dynamic Menu
The <asp:Menu> control displays a standard site navigation menu.
Code Example:
<asp:SiteMapDataSource id="nav1" runat="server" />
<form runat="server">
<asp:Menu runat="server" DataSourceId="nav1" />
</form>
The <asp:Menu> control in the example above is a placeholder for a server created navigation menu.
The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the
<asp:SiteMapDataSource> control.
The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).
TreeView
The <asp:TreeView> control displays a multi level navigation menu.
The menu looks like a tree with branches that can be opened or closed with + or - symbol.
Code Example:
The <asp:TreeView> control in the example above is a placeholder for a server created navigation menu.
The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the
<asp:SiteMapDataSource> control.
The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).
SiteMapPath
The SiteMapPath control displays the trail (navigation path) to the current page. The path acts as clickable
links to previous pages.
Unlike the TreeView and Menu control the SiteMapPath control does NOT use a SiteMapDataSource. The
SiteMapPath control uses the web.sitemap file by default.
Tips: If the SiteMapPath displays incorrectly, most likely there is an URL error (typo) in the
web.sitemap file.
Code Example:
<form runat="server">
<asp:SiteMapPath runat="server" />
</form>
The <asp:SiteMapPath> control in the example above is a placeholder for a server created site path
display.
What is ADO.NET?
ADO.NET is a part of the .NET Framework
ADO.NET consists of a set of classes used to handle data access
ADO.NET is entirely based on XML
ADO.NET has, unlike ADO, no Recordset object
First, import the "System.Data.OleDb" namespace. We need this namespace to work with Microsoft
Access and other OLE DB database providers. We will create the connection to the database in the
Page_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a connection
string which identifies the OLE DB provider and the location of the database. Then we open the database
connection:
<script runat="server">
sub Page_Load
dim dbconn
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" &
server.mappath("n.mdb"))
dbconn.Open()
end sub
</script>
Note: The connection string must be a continuous string without a line break!
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" &
server.mappath("n.mdb"))
dbconn.Open()
sql="SELECT * FROM customers"
dbcomm=New OleDbCommand(sql,dbconn)
end sub
</script>
Create a DataReader
The OleDbDataReader class is used to read a stream of records from a data source. A DataReader is
created by calling the ExecuteReader method of the OleDbCommand object:
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
sql="SELECT * FROM customers"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
end sub
</script>
dbread.Close()
dbconn.Close()
Bind to a Repeater Control
Then we bind the DataReader to a Repeater control:
Example
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
sql="SELECT * FROM customers"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>
<html>
<body>
<form runat="server">
<asp:Repeater id="customers" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Container.DataItem("companyname")%></td>
<td><%#Container.DataItem("contactname")%></td>
<td><%#Container.DataItem("address")%></td>
<td><%#Container.DataItem("city")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
Insert a record
<script runat=server>
conPubs.Open();
object ret = cmdSelect.ExecuteScalar();
if (ret!=null) {
lblPhone.Text = ret.ToString();
} else {
lblPhone.Text = " not found.";
}
conPubs.Close();
}
FormView is a data-bound user interface control that renders a single record at a time from its
associated data source, optionally providing paging buttons to navigate between records. It is
similar to the DetailsView control, except that it requires the user to define the rendering of each
item using templates, instead of using data control fields.
The main difference between DetailsView and FormView is that DetailsView has a built-in tabular
rendering, whereas FormView requires a user-defined template for its rendering. The FormView
and DetailsView object model are very similar otherwise.
The DetailsView control binds to a data source control. The data source control handles the
details of connecting to a data store and returning the selected data. Binding the DetailsView
control to data is as simple as setting the DataSourceID property declaratively. Also, the code
option is available.
The operations will depend upon the data source, but the DetailsView control allows you to page,
update, insert, and delete data from the underlying data source, as long at the operations are
allowed by the underlying data source and respective SQL commands are defined. In keeping
with the GridView control, the DetailsView control can easily be used without code.
GridView is the way to go for you. It will display tabular data (rows/columns) for you with options for
paging and sorting.
FormView and DetailsView is used as "properties" forms, like something that shows the details when you
have clicked on one of the items in the (GridView) list.
The difference between FormView and DetailsView is that FormView is template-based, so you have
more control over how the data is rendered.
1)datagrid and gridview both have same functionality to display your data in the form of a table.
Datagrid is used in Windows Application whereas gridview is used in Web Applications.
2)The Repeater control is used to display a repeated list of items that are bound to the control.
3)The DataList control is, like the Repeater control, used to display a repeated list of items that
are bound to the control. However, the DataList control adds a table around the data items by
default.
4)FormView is a data-bound user interface control that renders a single record at a time from its
associated data source, optionally providing paging buttons to navigate between records.
5)DetailsView is a data-bound user interface control that renders a single record at a time from its
associated data source, optionally providing paging buttons to navigate between records. It is
similar to the Form View of an Access database, and is typically used for updating and/or
inserting new records. It is often used in a master-details scenario where the selected record of
the master control (GridView, for example) determines the DetailsView display record.
GridVIew :
--------
The GridView control is the workhorse of the ASP.NET 2.0 Framework. It is one of the most
feature-rich and complicated of all the ASP.NET controls. The GridView control enables you to
display, select, sort, page, and edit data items such as database records.
You also get the chance to tackle several advanced topics. For example, we can highlight certain
rows in a GridView depending on the data the row represents.
DetailsView and FormView Controls :
----------- --- -------- --------
The DetailsView and FormView controls, these controls enable us to work with a single data item
at a time. Both controls enable you to display, edit, insert, and delete data items such as
database records. Furthermore, both controls enable you to page forward and backward through
a set of data items.
The difference between the two controls concerns the user interface that the controls render. The
DetailsView control always renders each field in a separate HTML table row. The FormView
control, on the other hand, uses a template that enables you to completely customize the user
interface rendered by the control.
A DetailsView control renders an HTML table that displays the contents of a single database
record. The DetailsView supports both declarative and programmatic databinding.
You can use the FormView control to do anything that you can do with the DetailsView control.
Just as you can with the DetailsView control, you can use the FormView control to display, page,
edit, insert, and delete database records. However, unlike the DetailsView control, the FormView
control is entirely template driven
The FormView control provides you with more control over the layout of a form. Furthermore,
adding validation controls to a FormView is easier than adding validation controls to a
DetailsView control.
Repeater and DataList Controls :
-------- --- -------- --------
Both the Repeater and DataList controls helps us to display a set of data items at a time. For
example, you can use these controls to display all the rows contained in a database table.
The Repeater control is entirely template driven. You can format the rendered output of the
control in any way that you please. For example, you can use the Repeater control to display
records in a bulleted list, a set of HTML tables, or even in a comma-delimited list.
The DataList control is also template driven. However, unlike the Repeater control, the default
behavior of the DataList control is to render its contents into an HTML table. The DataList control
renders each record from its data source into a separate HTML table cell.
The Repeater control provides you with the maximum amount of flexibility in rendering a set of
database records. You can format the output of the Repeater control in any way that you please.
The DataList control, like the Repeater control, is template driven. Unlike the Repeater control, by
default, the DataList renders an HTML table. Because the DataList uses a particular layout to
render its content, you are provided with more formatting options when using the DataList control.
GridView is new version and extension of earlier asp.net 1.1 Gridview in ASP.NET 2.0 and
onwards versions.
GridView is used for control, editing data, your own custom template, sorting kind of scenarios
but you can not customize everything.
Repeater – Repeater is used when you want to just read your data, Read Only but here you can
customize everything, repeater provide full control for UI.
DetailsView -
DetailView mostly used with GridView for Master Detail relationship, where master details are
shown using GridView and when you click a particular row, you can show further details of
individual row using DetailView either at the same page or at separate page. Here you can read,
edit and create (add a new row/record)
FormView - Read/Edit/Create FormView is more over same as detailsview and used similarly.
DataList - Read/Edit