ASP .Net Notes
ASP .Net Notes
Net
The ASP.NET life cycle could be divided into two groups:
When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events
are available, which could be overridden according to the need of the application. In other
words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components
on the page, except the directives, are part of this control tree. You can see the control tree by
adding trace= "true" to the page directive. We will cover page directives and tracing under
'directives' and 'event handling'.
The page life cycle phases are:
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen
at any stage of the page life cycle. It also helps in writing custom controls and initializing
them at right time, populate their properties with view-state data and run control behavior
code.
Following are the different stages of an ASP.NET page:
Page request - When ASP.NET gets a page request, it decides whether to
parse and compile the page, or there would be a cached version of the page;
accordingly the response is sent.
Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.
Page initialization - At this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and the themes are applied. For a new
request, postback data is loaded and the control properties are restored to the
view-state values.
Page load - At this stage, control properties are set using the view state and
control state values.
Validation - Validate method of the validation control is called and on its
successful execution, the IsValid property of the page is set to true.
Postback event handling - If the request is a postback (old request), the
related event handler is invoked.
Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of
page.
Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.
Attributes Description
The Assembly directive links an assembly to the page or the application at parse time. This
could appear either in the global.asax file for application-wide linking, in the page file, a user
control file for linking to a page or user control.
The basic syntax of Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:
Attributes Description
The control directive is used with the user controls and appears in the user control (.ascx)
files.
The basic syntax of Control directive is:
<%@ Control Language="C#" EnableViewState="false" %>
The attributes of the Control directive are:
Attributes Description
Strict For VB language, tells the compiler to use the option strict
mode.
The Implement directive indicates that the web page, master page or user control page must
implement the specified .Net framework interface.
The basic syntax for implements directive is:
<%@ Implements Interface="interface_name" %>
The Import directive imports a namespace into a web page, user control page of application.
If the Import directive is specified in the global.asax file, then it is applied to the entire
application. If it is in a page of user control page, then it is applied to that page or control.
The basic syntax for import directive is:
<%@ namespace="System.Drawing" %>
The Master directive specifies a page file as being the mater page.
The basic syntax of sample MasterPage directive is:
<%@ MasterPage Language="C#" AutoEventWireup="true"
CodeFile="SiteMater.master.cs" Inherits="SiteMaster" %>
The MasterType directive assigns a class name to the Master property of a page, to make it
strongly typed.
The basic syntax of MasterType directive is:
<%@ MasterType attribute="value"[attribute="value" ...] %>
The Page directive defines the attributes specific to the page file for the page parser and the
compiler.
The basic syntax of Page directive is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" Trace="true" %>
The attributes of the Page directive are:
Attributes Description
AutoEventWireup The Boolean value that enables or disables page events that are
being automatically bound to methods; for example,
Page_Load.
ClientTarget The browser for which the server controls should render
content.
EnableViewState The Boolean value that enables or disables view state across
page requests.
ErrorPage URL for redirection if an unhandled page exception occurs.
ValidateRequest The Boolean value that indicates whether all input data is
validated against a hardcoded list of values.
The PreviousPageType directive assigns a class to a page, so that the page is strongly typed.
The basic syntax for a sample PreviousPagetype directive is:
<%@ PreviousPageType attribute="value"[attribute="value" ...] %>
The Reference directive indicates that another page or user control should be compiled and
linked to the current page.
The basic syntax of Reference directive is:
<%@ Reference Page ="somepage.aspx" %>
The Register derivative is used for registering the custom server controls and user controls.
The basic syntax of Register directive is:
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>
The provider model is not an application feature that end users can see with their own eyes.
In itself, it doesn't make an application show a richer content, run faster, or be more
responsive. The provider model is an infrastructural feature that improves an application's
architecture by enabling developers and architects to operate under the hood of some system
components. At the same time, it enables developers to build new components that expose
hooks for clients to plug in and customize behavior and settings. Implementing the strategy
pattern doesn't transform an application into an open-source project, allowing anybody to
modify anything. It simply means that you have a simple, elegant, and effective pattern to
make certain parts of your application customizable by clients. At the same time, the
ASP.NET implementation of the pattern the provider model makes you capable of
customizing certain parts of the ASP.NET runtime environment through special classes
named providers from which you can derive your own.
Can you see the big picture? There are modules in ASP.NET that force you to take (or leave)
a fixed schema of data, a fixed storage medium, and a fixed internal behavior. The most that
you can do is (sometimes) avoid using those modules and write your own from scratch, as we
outlined in the membership example. However, rolling your own replacement is not
necessarily a smart move. You end up with a proprietary and application-specific system that
is not automatically portable from one application to another. In addition, if you hire new
people, you have to train those people before they get accustomed to using your API. Finally,
you have to put forth a lot of effort to make such a proprietary API general enough to be
reusable and extensible in a variety of contexts. (Otherwise, you get to reinvent the wheel
time after time.)
In which way is the provider model a better solution? In the first place, it supplies a well-
documented and common programming interface to perform common tasks. In addition, you
gain the ability to completely control the internal business and data access logic of each API
that falls under its umbrella.
In the end, in ASP.NET 1.1 you often have no other choice than writing your own API to roll
certain functions the way you want. In ASP.NET 2.0, the provider model offers a much better
alternative. So much better that it's practically a crime not to use it.
Figure 1-7 revisits Figure 1-6 in light of the provider model. ASP.NET 2.0 makes available a
bunch of static methods on a global class Membership. (We'll cover the membership API in
great detail in Chapter 15.) At the application level, you always invoke the same method to
perform the same operation (for example, validating user credentials, creating new users,
changing passwords.) Below this common API, though, you can plug in your own provider to
do the job just the way you want. Writing a new provider is as easy as deriving a new class
from a known base and overriding a few well-known methods. The selection of the current
provider for a given task takes place in the configuration file.
Figure 1-7: Membership revisited to use the provider model in ASP.NET 2.0.
You can use it by by choosing Add > New Item > Global Application Class in Visual Studio.
Once you've added the file, you can add code under any of the events that are listed (and
created by default, at least in Visual Studio 2008):
Application_Start
Application_End
Session_Start
Session_End
Application_BeginRequest
Application_AuthenticateRequest
Application_Error
There are other events that you can also hook into, such as "LogRequest".
Application_Init: Fired when an application initializes or is first called. It's invoked for all
HttpApplication object instances.
Application_Start: Fired when the first instance of the HttpApplication class is created. It
allows you to create objects that are accessible by all HttpApplication instances.
Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's
fired only once during an application's lifetime.
Application_BeginRequest: Fired when an application request is received. It's the first event
fired for a request, which is often a page request (URL) that a user enters.
Application_AuthorizeRequest: Fired when the security module has verified that a user can
access resources.
Session_Start: Fired when a new user visits the application Web site.
Session_End: Fired when a user's session times out, ends, or they leave the application Web
site.
7. States
View State
The view state is the state of the page and all its controls. It is automatically maintained
across posts by the ASP.NET framework.
When a page is sent back to the client, the changes in the properties of the page and its
controls are determined, and stored in the value of a hidden input field named
_VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to the
server with the HTTP request.
The view state could be enabled or disabled for:
The entire application by setting the EnableViewState property in the
<pages> section of web.config file.
A page by setting the EnableViewState attribute of the Page directive, as <%@
Page Language="C#" EnableViewState="false" %>
A control by setting the Control.EnableViewState property.
Session State
When a user connects to an ASP.NET website, a new session object is created. When session
state is turned on, a new session state object is created for each new request. This session
state object becomes part of the context and it is available through the page.
Session state is generally used for storing application data such as inventory, supplier list,
customer record, or shopping cart. It can also keep information about the user and his
preferences, and keep the track of pending operations.
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
Application State
The ASP.NET application is the collection of all web pages, code and other files within a
single virtual directory on a web server. When information is stored in application state, it is
available to all the users.
To provide for the use of application state, ASP.NET creates an application state object for
each application from the HTTPApplicationState class and stores this object in server
memory. This object is represented by class file global.asax.
Application state data is generally maintained by writing handlers for the events:
Application_Start
Application_End
Application_Error
Session_Start
Session_End
The Label control displays text at a particular position on a Web page. Generally Label
control is used as the caption of a TextBox.
Literal control
It is light weight control. The Literal Control is similar to the Label Control but it does not
support properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, etc.
Also you cannot apply a style to a literal control. It is used to display static text on a Web
page without adding additional properties or HTML tags.
TextBox control
The TextBox control is frequently used and one of the most important control. It is used to
collect information from a user. It is an input control which is used to input the data.
The TextBox control contains an important property called TextMode. By using this property
you can set textbox as
SingleLine
MultiLine
Password
SingleLine mode is default mode of textbox control and allows the user to enter data in a
single line of text.
Password mode masks (text is hidden) the values entered by the user.
MultiLine mode enables user to enter text in more than one line. You can use MultiLine
mode, in combination with the Columns and Rows properties. Column specifies the number
of columns (Width) and rows specify the number of rows (Height) to display.
Another important property of textbox control is MaxLength. It sets the limit on the number
of character that a user can enter into textbox.
TextChanged: It fires, when you change the content or text of the textbox control.
TextChanged event only fire, when AutoPostBack property has the value True. By default
AutoPostBack property has the value false.
If you change the text of the TextBox control and press tab key from the keyboard, the form
is automatically posted back to the server.
Button Controls
There are three types of button control available in ASP.NET:
Button
Link Button
Image Button
Button control
Button control postbacks the web page to webserver, when user clicks the button. A Button
control can be used as a submit button (default) or a command button.
You can also use Button control as a command button. It is useful when you want to group a
set of buttons. Button control has property called CommandName. Assign unique
CommandName value for each button. Create a single command event handler explicitly, that
will handle the event of all command buttons.
Suppose that you have four buttons as given below and want to create all buttons as a
command button.
Provide a unique CommandName to each button. As example First, Last, Previous, Next.
Example: Default.aspx
Default.aspx.cs
using System;
using System.Web.UI.WebControls;
using System.Drawing;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Navigate_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
Response.Write("First");
break;
case "Previous":
Response.Write("Previous");
break;
case "Next":
Response.Write("Next");
break;
case "Last":
Response.Write("Last");
break;
}
}
}
CausesValidation property: It checks the page validation. By default this property is true
for button control. If you set CauseValidation value to false, then it will bypass the page
validation.
LinkButton
LinkButton control displays a link instead of a push button. By default, a LinkButton control
is a Submit button.
PostBackUrl: It posts a form to a particular page when the LinkButton control is clicked.
ValidationGroup: The group of controls when the LinkButton control causes posts back to
the server.
OnClick: Attach a server side method that will fire when this button will be clicked.
OnClientClick: You can attach a client-side script that executes when the LinkButton is
clicked.
ImageButton
The ImageButton control is similar to Button and LinkButton controls but it always displays
an image. It works as a clickable image. Most of the properties are same as Button or
LinkButton.
The main difference is ImageUrl and AlternateText property. ImageUrl Gets or Sets the
location of the image. AlternateText property provides alternate text for the image.
Let us take an example that will show the use of TextBox and Different type of Button.
Example: Default.aspx
Checked: It is used to check if the check box is checked or not. This is a boolean property.
Text: It is used to get or set the text associated with the check box control. This is a string
property.
TextAlign: It enables you to set the text right or left of the check box. By default TextAlign
property is set to right.
AutoPostBack: If you want that when you change the status of checkbox (check or
uncheck), then set AutoPostBack property true. By default this property is set to false.
Methods:
Focus(): It sets the input focus, to a specific checkbox. Call this method for that check box
control.
Events:
CheckedChanged: This event is fired when the checked status of the checkbox control is
changed. AutoPostBack property should be set as true to fire this event.
RadioButton Control
Radio Button control is used, when you want to select only one option from the available
choices. RadioButton control works in a group. There may be more than one group of radio
button. You can select only one RadioButton control from particular radio button group.
9. TreeView
The TreeView control is an object model in ASP.Net which allows creation of nodes
dynamically. It will have the Root, Parent and Leaf.
The TreeView control has properties and events. It has some characteristics.
There are some properties that are useful for defining the behavior of the TreeView. These
properties are Boolean value based.
You can control static display behavior by using the StaticDisplayLevels property of the
Menu control. The StaticDisplayLevels property indicates how many levels to display
statically from the root of the menu. For example, if StaticDisplayLevels is set to 3, your
menu will be expanded to statically display its first three levels. The minimum static display
level is 1, and the control will throw an exception if the value is set to 0 or a negative number.
You can define content for the Menu control in two ways: by adding individual MenuItem
objects (declaratively or programmatically), and by data binding the control to an XML data
source.
Adding Menu Items Manually
You can add individual menu items to the control by specifying them in the Items property.
The Items property is a collection of MenuItem objects. The following example shows the
declarative markup for a Menu control with three items, each of which has two child items:
</asp:Menu>
Google recognized this problem and introduced site maps formatted as XML files. Site maps
are accepted later by Microsoft and Yahoo. ASP.NET 2.0 goes one step beyond and provides
new .sitemap XML files that work with Menu, TreeView and SiteMapPath controls to enable
easier navigation. Although Google site map and ASP.NET .sitemap are both XML files,
they don't use same schema.
Web Parts now a day's most of the websites is using this technology extensively.
If you just clearly observe any of the websites, you can observe the difference web parts
concept is making on the web pages.
The Level of interactive Ness we can find is that we feel like we are designing that web page.
So what if we can design and code our own WebPages that will accumulate the concept of
web parts. we can code and explore that as easily as we have done with the other controls in
the previous sessions.
We can compose web parts pages from "web parts", which can be web controls, user
controls.
In this exercise, lets see the usage of Web Part Manager, WebPartZone and how to use
conventional Web Controls (ASP.NET CONTROLS/User Controls) as Web Parts.
Web parts manager consists of each division of the web parts in the order of the module
consistency.
A single Web Parts page can ONLY have one instance of a "WebPartManager Control".
The usage of WebPartManager control is that it manages all the other Web Parts controls on
that page, including Web Part Zones (Web Zone class).
The WebPartManager control, in turn, maintains a collection of all the Web Part controls on a
page in its Web Parts collection. This doesn't have any User Interface and is not visible at run
time (similar to the Timer Control)
Step 5: After adding the Web Part Zone Controls, the page should look like this:
Figure 1
Step 6: Right Click in the solution Explorer and select "Add New Item" from the menu.
Step 7: Select "Web User Control" as the type and name it as "myusercontrol.ascx".
Step 8: Add a table having 1 row and 1 column and add the following text inside the <td>
</td>
Step 9: "Welcome to webparts home". The web parts HomePage is highly personalizable. To
personalize this page, use the links in the upper corner.
Step 10: HTML Content can be added basing on your interest.
Step 11: Switch to Design View and drag and drop myusercontrol.ascx in webpartzone1.
Step 12: Now your Page in Design View will look similar to the one below:
Figure 2
Step 13: Change the title of the user control to "Webparts". This can be done by selecting the
user control and switching to "Source".
Step 14: Inside the <Zone Template> you can find this tag:
1. <uc1:myusercontrol ID="Myusercontrol1" runat="server" />
The Beauty of "Web Parts" is that it maintains its own Database for storing the User
Preferences by assigning a unique User ID to each and every user accessing the "Web Parts".
Step 19: On the Browser you can see a smart tag (the drop down arrow in blue on the top
right hand corner for each zone). If you click on any of the tags, your pages will look similar
to this:
Figure 4
Figure 5
Step 22: Close your Browser and come back to the Design Part of the Page.
Step 23: Now execute your application again to check the preferences are saved or not.
Step 24: Interestingly, if you can observe the settings you have made to Zone1 are applied
and you can see that WebPartZone1 is still minimized.
Step 25: So your application on the Browser should be similar to this:
Figure 6
A key feature of Web Parts is the ability of end users to personalize Web pages and save their
personalized settings. One aspect of modifying Web Parts pages includes editing the
appearance, layout, behavior, and other properties of the visible WebPart controls.
Contains the code for a ZIP Code interface, and two WebPart controls acting as
the provider and the consumer for a connection.
An important aspect of creating ASP.NET Web pages for user input is to be able to check
that the information users enter is valid. ASP.NET provides a set of validation controls that
provide an easy-to-use but powerful way to check for errors and, if necessary, display
messages to the user.
RequiredFieldValidation Control
The RequiredFieldValidator control is simple validation control, which checks to see if the
data is entered for the input control. You can have a RequiredFieldValidator control for each
form element on which you wish to enforce Mandatory Field rule.
1. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
2. Style="top: 98px; left: 367px; position: absolute; height: 26px; width: 162px"
3. ErrorMessage="password required" ControlToValidate="TextBox2">
4. </asp:RequiredFieldValidator>
CompareValidator Control
The CompareValidator control allows you to make comparison to compare data entered in an
input control with a constant value or a value in a different control.
It can most commonly be used when you need to confirm password entered by the user at the
registration time. The data is always case sensitive.
1. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Styl
e="top: 145px;
2. left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage=
"password required"
3. ControlToValidate="TextBox3"></asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator Server Control is another validator control, which checks to see if a
control value is within a valid range. The attributes that are necessary to this control are:
MaximumValue, MinimumValue, and Type.
1. <asp:RangeValidator ID="RangeValidator1" runat="server"
2. Style="top: 194px; left: 365px; position: absolute; height: 22px; width: 105px"
3. ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumVal
ue="100" MinimumValue="18" Type="Integer"></asp:RangeValidator>
RegularExpressionValidator Control
It is used to validate complex expressions. These expressions can be phone number, email
address, zip code and many more. Using Regular Expression Validator is very simple. Simply
set the ValidationExpression property to any type of expression you want and it will validate
it.
ValidationSummary
ASP.NET has provided an additional control that complements the validator controls.
The ValidationSummary control is reporting control, which is used by the other validation
controls on a page.
You can use this validation control to consolidate errors reporting for all the validation errors
that occur on a page instead of leaving this up to each and every individual validation control.
The validation summary control will collect all the error messages of all the non-valid
controls and put them in a tidy list.
1. <asp:ValidationSummary ID="ValidationSummary1" runat="server"
2. style="top: 390px; left: 44px; position: absolute; height: 38px; width: 625p
x" />
CustomValidator Control
You can solve your purpose with ASP.NET validation control. But if you still don't find
solution you can create your own custom validator control.
The CustomValidator Control can be used on client side and server side. JavaScript is used to
do client validation and you can use any .NET language to do server side validation.
I will explain you CustomValidator using server side. You should rely more on server side
validation.
14. GridView:
Introduction
The GridView control displays the values of a data source in a table. Each column represents
a field, while each row represents a record. The GridView control supports the following
features:
Binding to data source controls, such as SqlDataSource.
Built-in sort capabilities.
Built-in update and delete capabilities.
Built-in paging capabilities.
Built-in row selection capabilities.
Programmatic access to the GridView object model to dynamically set
properties, handle events, and so on.
Multiple key fields.
Multiple data fields for the hyperlink columns.
Customizable appearance through themes and styles.
Creating a GridView
1. <asp:GridView ID="gridService" runat="server" AutoGenerateColumns="false
" ShowFooter="true" >
2. <Columns>
3. <asp:TemplateField ItemStyle-Width="30px" HeaderText="SR.
NO">
4. <ItemTemplate>
5. <asp:Label ID="lblID" runat="server"
6. Text='<%#Eval("service_id")%>'></asp:Label>
7. </ItemTemplate>
8. </asp:TemplateField>
9. <asp:TemplateField ItemStyle-Width="600px" HeaderText="Ser
vice">
10. <ItemTemplate>
11. <asp:Label ID="lblService" runat="server" Text='<
%#Eval("service_name")%>'></asp:Label>
12. </ItemTemplate>
13. <EditItemTemplate>
14. <asp:TextBox ID="txtService" runat="server" Text='<
%#Eval("service_name")%>'></asp:TextBox>
15. </EditItemTemplate>
16. <FooterTemplate>
17. <asp:TextBox ID="txtService" runat="server"></
asp:TextBox>
18. </FooterTemplate>
19. </asp:TemplateField>
20. <asp:TemplateField ItemStyle-Width="100px" HeaderText="Ser
vice Photo">
21. <ItemTemplate>
22. <img src='<%# Eval("service_image")%>' alt='<%#
23. Eval("service_image")%>' height="50px"
24. width="50px" />
25. </ItemTemplate>
26. <EditItemTemplate>
27. <asp:FileUpload ID="fuService" runat="server" />
28. </EditItemTemplate>
29. <FooterTemplate>
30. <asp:FileUpload ID="fuService" runat="server" />
31. </FooterTemplate>
32. </asp:TemplateField>
33. <asp:TemplateField>
34. <ItemTemplate>
35. <asp:LinkButton ID="lnkRemove" runat="server" Comman
dArgument='<%#
36. Eval("service_id")%>'
37. OnClientClick="return confirm('Do you want to delete?')"
38. Text="Delete"></asp:LinkButton>
39. </ItemTemplate>
40. <FooterTemplate>
41. <asp:Button ID="btnAdd" runat="server" Text="Add" OnCl
ick="AddService"/>
42. </FooterTemplate>
43. </asp:TemplateField>
44. <asp:CommandField ShowEditButton="True" />
45. </Columns>
46. </asp:GridView>
Binding GridView
1. gridService.DataSource = Table_Student;
2. gridService.DataBind();
15.Data List Control
Introduction
Creating DataList
1. <asp:DataList ID="dl1" runat="server"
2. RepeatDirection="Horizontal"
3. RepeatColumns="3">
4. <HeaderTemplate>
5. <table>
6. <tr>
7. <td>
8. <h1>Student Information</h1>
9. </td>
10. </tr>
11. </table>
12. </HeaderTemplate>
13. <ItemStyle CssClass="itemstyle" />
14. <ItemTemplate>
15. <table border="1">
16. <tr>
17. <td>Employee ID:</td>
18. <td>
19. <asp:Label ID="lblempid" runat="server" Text='<%# Eva
l("EmpId") %>'>
20. </asp:Label>
21. </td>
22. <td rowspan="5">
23. <asp:Image ID="empimg" runat="server" ImageUrl='
24. <%# "~/Images/" + Eval("EmpImage") %>' Height="1
80px" Width="200px" />
25. </td>
26. </tr>
27. <tr>
28. <td>Employee Name:</td>
29. <td>
30. <asp:Label ID="lblempname" runat="server" Text='<
%# Eval("EmpName") %>'>
31. </asp:Label>
32. </td>
33. </tr>
34.
35.
36. </table>
37. </ItemTemplate>
38.
39. </asp:DataList>
Binding DataList
1. protected void Page_Load(object sender, EventArgs e)
2. {
3. if (!IsPostBack)
4. {
5. Bind();
6. }
7. }
8. public void Bind()
9. {
10. SqlCommand cmd = new SqlCommand("select * from Employee", con);
11. SqlDataAdapter da = new SqlDataAdapter(cmd);
12. DataSet ds = new DataSet(); //dataset is set of tables
13. da.Fill(ds, "Employee");
14.
15. // binding datalist with 0th table of dataset
16.
17. dl1.DataSource = ds.Tables[0];
18. dl1.DataBind();
19. }
}
private void BindDetailsView()
{
FormView Control is introduced with ASP.NET 2.0. It is often used in master/details scenario
with GridView, DataList or Repeater control. FormView Control is similar to DeatilsView control.
Both controls enable showing of single record from data source. The main difference between
FormView and DeatilsView controls is that FormView control allows using of templates for
displaying a record instead of row fields used in DetailsView. Unlike DetailsView, FormView
control doesn't have predefined data layout. Developer needs to create a template first and
specify controls and formatting to display single record from data source. Because of that
developer have full control over layout and it is pretty easy to add validation capabilities.
<asp:FormView
id="frmBooks"
DataSourceID="SqlDataSource1"
Runat="server">
<ItemTemplate>
<b><u><%# Eval("TITLE")%></u></b>
<br />
<b>Serial Number:</b>
<%# Eval("ID")%>
<br />
<b>Author:</b>
<%# Eval("AUTHOR")%>
<br />
<b>Price:</b>
<%# Eval("PRICE")%>
</ItemTemplate>
</asp:FormView>
18.Repeater Control
The Repeater control is used to display a repeated list of items that are
bound to the control. The Repeater control may be bound to a database
table, an XML file, or another list of items.
Repeater is a Data Bind Control. Data Bind Controls are container controls.
Data Binding is the process of creating a link between the data source and
the presentation UI to display the data. ASP .Net provides rich and wide
variety of controls, which can be bound to the data.
A SqlDataSource control is added to the webform using markup or by dragging it from the
Toolbox and dropping it on the web form. The code below shows the markup to create a
SqlDataSource control.