0% found this document useful (0 votes)
620 views49 pages

Data Bound Controls

The document discusses data-bound controls in ASP.NET 2.0. It describes the hierarchy of data-bound controls with the BaseDataBoundControl class at the top branching into DataBoundControl and HierarchicalDataBoundControl. Simple data-bound controls include AdRotator and list controls like BulletedList. Composite controls include GridView, FormView, and DetailsView. GridView provides a tabular view of data and supports sorting, paging, and editing. DetailsView and FormView are for updating and inserting single records.

Uploaded by

AMessi Young
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
620 views49 pages

Data Bound Controls

The document discusses data-bound controls in ASP.NET 2.0. It describes the hierarchy of data-bound controls with the BaseDataBoundControl class at the top branching into DataBoundControl and HierarchicalDataBoundControl. Simple data-bound controls include AdRotator and list controls like BulletedList. Composite controls include GridView, FormView, and DetailsView. GridView provides a tabular view of data and supports sorting, paging, and editing. DetailsView and FormView are for updating and inserting single records.

Uploaded by

AMessi Young
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

Data-Bound Controls

Introduction
The DataGrid is the principal control of most data-driven ASP.NET 1.x applications. It generates a tabular representation of data and offers advanced functionality such as paging, sorting, and in-place editing. Like all ASP.NET 1.x controls, the DataGrid is fully supported in ASP.NET 2.0 but is partnered with a newer control that is meant to replace it in the long run. The new grid control,GridView, is complemented by other view controls, such as DetailsView and FormView.

Hierarchy of Data-Bound Controls


All controls descend from the same base class BaseDataBoundControl.

BaseDataBoundControl branches off into two more specific child classes DataBoundControl and HierarchicalDataBoundControl.

The class diagram for data-bound controls in ASP.NET 2.0

The DataBoundControl Base Class


DataBoundControl is an abstract base class that defines the common characteristics of flat, nonhierarchical controls that use a data source. The class determines how a data-bound control binds to a collection of data items or to a data source object.

You can group data-bound controls into three categories: simple, composite, and hierarchical controls.
Properties of the DataBoundControl Class: The DataBoundControl class inherits from WebControl and can thus have all the visual and style properties defined on the base class. Examples of visual properties include BackColor, ForeColor, Font, BorderStyle, and the new SkinID.

Data-Related Properties of DataBoundControl


Property Description:
DataMember: Selects the list of data that the control should bind to when the datasource contains more than one list. For example, it specifies the name of the DataTable to pick up when the control is bound to a DataSet. DataSource: Indicates the data source to bind to. The data source must be an objectthat implements the IEnumerable or IListSource interface. DataSourceID: The ID of the data source object to use to retrieve data.

Simple Data-Bound Controls:


ASP.NET 2.0 has two types of simple data-bound controlsthe AdRotator control and list controls.The AdRotator control is extended to support data sources using the default data-binding model. Basically, the ASP.NET 2.0 AdRotator control is the same as the one in version 1.x but with full support for data binding.

Code Usage
<asp:accessdatasource runat="server id="MyAccessSource" DataFile="data/advert.mdb" SelectCommand="SELECT * FROM AdTable /> <asp:adrotator id="Adrotator1 runat="server ImageUrlField="Image" NavigateUrlField="Url" AlternateTextField="AltText" DataSourceID="MyAccessSource />

The BulletedList Control


use the Bulleted List control to create a list of items formatted with bullets. usually do not statically generate the list items fill the bulleted list via its data binding capabilities.

Code Usage
<asp:SqlDataSource runat="server id="MySource ConnectionString="SERVER=;DATABASE=northwi nd;UID=;" DataSourceMode="DataSet SelectCommand="SELECT customerid, companyname FROM customers WHERE country=Italy /> <asp:BulletedList runat="server id="custList" BulletImageUrl="images/bullet.gif BulletStyle="CustomImage DisplayMode="LinkButton DataSourceID="MySource DataTextField="companyname />

The CompositeDataBoundControl
The CompositeDataBoundControl class, which inherits from DataBoundControl, is marked as abstract and declares and implements the Controls property. The Controls property stores references to child controls.TheCompositeDataBoundControl class also exposes the CreateChildControls method.

Examples of Composite Data-Bound Controls


ASP.NET 2.0 defines a few key composite databound controls, such as Grid-View, FormView, and DetailsView. The GridView control can be considered the successor to the DataGrid. The DetailsView control provides a flexible and customizable user interface but a fixed layout. The FormView control is fully templatized.

The DetailsView and FormView controls are typically employed to update existing records and insert new ones.

The GridView Object Model


The GridView control provides a tabular, gridlike view of the contents of a data source. Each column represents a data source field, and each row represents a record.

The GridView Control in Action Simple Data Binding..

Code usage
<asp:TextBox runat="server ID="Initial MaxLength="1 /> <asp:SqlDataSource runat="server ID="MySource ConnectionString="SERVER=;DATABASE=northwind;UID= ;" SelectCommand="SELECT companyname, country FROM customers WHERE companyname LIKE @Initial + %"> <SelectParameters> <asp:ControlParameter Name="Initial ControlId="Initial PropertyName="Text /> </SelectParameters> </asp:SqlDataSource> <asp:GridView runat="server id="grid DataSourceID="MySource /> Note:Setting the DataSourceID property triggers the binding process, which runs the data source query and populates the user interface of the grid. You need not write any code.

Adaptive Rendering of GridView control


Another important difference between the DataGrid and GridView controls is that the adaptive rendering engine of Visual Studio 2005 server controls enables the GridView to adapt its HTML output to the characteristics of the browser( with special attention paid to mobile devices).

Adaptive Rendering of GridView control


Because of their limited screen size, mobile devices often require that the control reorganize the output to make it fit. For devices with small screens, the GridView shows only a single record per page and provides additional links to move between records.

Displaying Data
Like the DataGrid control, the GridView supports custom column fields through the Columns collection. If you want to display only a subset of the retrieved data fields or if you simply want to customize their appearance, you can populate the Columns collection with objects that represent columns of data.

Configuring Columns
To statically declare your columns in the .aspx source file, you use the <Columns> tag, as shown here: <columns> <asp:boundfield datafield="customerid headertext="ID /> <asp:boundfield datafield="companyname headertext="Company Name /> </columns>

A GridView composed of different types of columns


<columns> <asp:boundfield datafield="productname headertext="Product /> <asp:checkboxfield datafield="discontinued headertext="Discontinued /> <asp:buttonfield buttontype="Button text="Buy /> <asp:hyperlinkfield text="More Info... datanavigateurlfields="productid,productname datanavigateurlformatstring="/moreinfo.aspx?id={0} &name={1} /> </columns>

Templated Fields
A TemplateField column gives each row in the grid a personalized user interface that is completely defined by the page developer. You can define templates for various rendering stages, including the default view, in-place editing, header, and footer.

Sorting Data
The GridView is designed to take advantage of specific capabilities of the underlying data source control. In this way, the grid control can handle common operations on data such as sorting, paging, updating, and deleting.

To enable sorting on a GridView, the following code would suffice.

Sorting Data
<asp:gridview runat="server id="MyGridView DataSourceID="MySource AllowSorting="true AutoGenerateColumns="false"> <Columns> <asp:boundfield datafield="productname headertext="Product sortexpression="productname /> <asp:boundfield datafield="quantityperunit headertext="Packaging /> </Columns> </asp:gridview>

Sorting Data
When you run this code, each column that has a nonempty SortExpression property displays its header text as a hyperlink. When a user clicks there, page posts back and returns with the grids contents sorted accordingly.

Paging The Data-1


The ability to scroll a potentially large set of data is an important but challenging feature for modern, distributed applications. An effective paging mechanism allows customers to interact with a database without holding resources. Like the DataGrid, the GridView control provides a built-in mechanism for paging over the supplied data source.

To enable paging, all you do is enable paging capabilities on the control. The property to use is AllowPaging.
<asp:gridview runat="server id="MyGridView datasourceid="MySource autogeneratecolumns="false" allowpaging="true allowsorting="true onrowcreated="MyGridView_RowCreated > <pagersettings firstpagetext="7 lastpagetext="8 nextpagetext="4 prevpagetext="3 mode="NextPrevFirstLast /> <pagerstyle font-name="webdings /> <columnfields> <asp:boundfield datafield="productname headertext="Product sortexpression="productname /> <asp:boundfield datafield="quantityperunit headertext="Packaging /> </columnfields> </asp:gridview>

Paging The Data-3


When the AllowPaging property is set to true, the grid displays a pagerbar. You can control the characteristics of the pager to a large extent through the <PagerSettings> and <PagerStyle> tags or their equivalent properties.

The pager can work in either of two modesdisplaying explicit page numbers or providing a relative navigation system

Paging The Data-4


The buttons are present to navigate to the next or previous page and even to the first or the last. Ad hoc properties NextPageText and PreviousPage- Text let you set the labels for these buttons as desired.

In-Place Editing and Updates


In-place editing refers to the grids ability to support changes to the currently displayed records. You enable in-place editing on a grid view by turning on the AutoGenerateEditButton Boolean property: <asp:gridview runat="server id="MyGridView datasourceid="MySource autogeneratecolumns="false autogenerateeditbutton="true"> </asp:gridview>

DetailsView Control-1
Many applications need to work on a single record at a time. ASP.NET 1.x has no built-in support for this scenario. Creating a single record view is possible, but it requires some coding. You have to fetch the record, bind its fields to a data-bound form. In ASP.NET 2.0, the DetailsView fulfills this role. It is the ideal complement to the GridView control for building, easily and effectively, hierarchical views of data.

DetailsView Control-2
Like the GridView, the DetailsView control can bind to any data source control and exploit its set of data operations. It can page, update, insert, and delete data items in the underlying data source as long as the data source supports these operations. The DetailsView control doesnt support templates. A fully templatized details view control is the FormView.

The DetailsView Control in Action


Building a record viewer with the DetailsView control is easy and quick. You just drop an instance of the control onto the Web form and add a few settings.

Code Usage
<asp:detailsview runat="server id="det datasourceid="MySource allowpaging="true" headertext="Employees"> <pagersettings firstpageimageurl="images/first.gif lastpageimageurl="images/last.gif nextpageimageurl="images/next.gif prevpageimageurl="images/prev.gif mode="NextPrevFirstLast /> </asp:detailsview>

As with the GridView, edit and delete operations for the DetailsView control are handled by the bound data source control, as long as the proper commands are defined and a key field is indicated through the DataKeyNames property: Continue

Code Usage-1
<asp:sqldatasource runat="server id="MySourceconnectionstring="server=;data base=northwind;UID=selectcommand="SELE CT employeeid, firstname,lastname, title, hiredate FROM employees updatecommand="UPDATE employees SET firstname=@firstname, lastname=@lastname, title=@title, hiredate=@hiredate WHERE employeeid=@employeeid" deletecommand="DELETE employees WHERE employeeid=@employeeid />.

Code Usage-2
<asp:detailsview runat="server id="det datasourceid="MySource allowpaging="true" headertext="Employees" datakeynames="employeeid" autogenerateeditbutton="true autogeneratedeletebutton="true"> <pagersettings firstpageimageurl="images/first.gif lastpageimageurl="images/last.gif nextpageimageurl="images/next.gif prevpageimageurl="images/prev.gif mode="NextPrevFirstLast /> </asp:detailsview>

The FormView Control


FormView is a new data-bound control that works like the templated version of the DetailsView control. It renders one record at a time picked from the associated data source and optionally provides paging buttons to navigate between records.

Two functional aspects mark the difference between FormView and DetailsView. First, the FormView control has ItemTemplate, EditItemTemplate, and InsertItemTemplate properties thatas youve already seenthe DetailsView lacks. Second, the FormView control lacks the command row, which is a sort of toolbar where available functions are grouped.

Displaying Data
<asp:FormView ID="EmpDetails runat="server DataSourceId="MySource AllowPaging="true"> <ItemTemplate> : </ItemTemplate> <EditItemTemplate> : </EditItemTemplate> < InsertItemTemplate > : </InsertItemTemplate> </asp:FormView>

Code Usage-1
The following code generates the page shown in the figure in previous slide: <asp:FormView runat="server id="EmpDetails datakeynames="employeeid" datasourceid="MySource allowpaging="true"> <ItemTemplate> <table style="border:solid 1px black;"> <tr> <td bgcolor="yellow width="50px align="center"> <b><%# Eval(employeeid) %></b></td> <td bgcolor="lightyellow > <b><%# Eval(lastname) %>, <%# Eval(firstname) %> </b></td> </tr> </table>.

Code Usage-2
<table style="font-family:Verdana;font-size:8pt;"> <tr> <td><b>Country</b></td> <td><%# Eval(country) %></td> </tr> <tr> <td><b>Hired</b></td> <td><%# Eval(hiredate", {0:d}) %></td> </tr> <tr> <td valign="top"><b>Notes</b></td> <td><%# Eval(notes) %></td> </tr> </table> <asp:Button Runat="server CommandName="Edit Text="Edit /> </ItemTemplate> </asp:FormView>

The Edit button is added using a classic <asp:Button> button with the Edit command name. This causes the FormView to switch from read-only mode to edit mode and display using the EditItemTemplate, if any is defined. In view mode, you use the Eval function to bind data fields to controls. Eval is useful only in read-only scenarios.

You might also like