Data Bound Controls
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.
BaseDataBoundControl branches off into two more specific child classes DataBoundControl and HierarchicalDataBoundControl.
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.
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 />
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.
The DetailsView and FormView controls are typically employed to update existing records and insert new ones.
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.
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>
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.
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.
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>
The pager can work in either of two modesdisplaying explicit page numbers or providing a relative navigation system
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.
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>
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.