280 likes | 436 Vues
Data Rendering and Templates Using Asp.NET. The DataGrid, DataList and Repeater controls are feature rich for displaying data. They BIND to a DataSource (property) which can be an arrayList, DB or XML file.
E N D
Data Rendering and TemplatesUsing Asp.NET • The DataGrid, DataList and Repeater controls are feature rich for displaying data. • They BIND to a DataSource (property) which can be an arrayList, DB or XML file. • Templates can be used to describe the way data is rendered. (DataGrid and DataList have default template settings). • Repeater Example • Simple List -repeater Example • Uses templates for formatting output • See Lecture11Samples.doc for source listings
DataGrid properties • Allowsorting: • eg sort by surname column of datasource • Allowpaging: • number of items to show set by Pagesize property • *AlternatingItemStyle: • Style of every alternate row eg background colour • *Footerstyle ; HeaderStyle; ItemStyle • *(Starred)items represent template items. • Example:edittemplate.aspx
DataList properties • Itemtemplate • AlterbnatingItemtemplate • EditItemtemplate • Provides editing controls (eg textboxes) for items set to edit (editmode = true)(default is itemtemplate, editmode= false) • Footertemplate and HeaderTemplate • SelectedItemTemplate • SeparatorTemplate • Template properties have to be set in tags and applied to dataitems • See repeater example
Repeater Control • Similar to DataList control BUT is Read Only • Useful for displaying rows of data. • Repeater Example • Simple List -repeater Example
Templates • List bound controls (datagrid, datalist and Repeater) support 5 types of templates • Header template • Rendered once before any data rows • Item Template • Rendered once for each data row • Alternating item template • Rendered for every alternate data row • Separator template • Elements to render between items, usually <BR><HR> • Footer template • Rendered once after all data rows have been rendered
Notes re the repeater control EG-0 • The page load event procedure makes a connection to the database, creates a dataset and binds it to two repeater controls • The first repeater control, replist, simply outputs data in a list • The second repeater control, reptable, uses Headertemplate,ItemTemplate, AlternatingItemTemplate and FooterTemplate
Notes re the repeater control EG-1 • Create the control and bind to a data source reptable.DataSource=ds.Tables("Authors").DefaultView reptable.DataBind() • Bind data in the repeater control to templates to describe how to display the data <asp:Repeater id="repTable" runat="server"> <HeaderTemplate> <table> <tr> <td style="font:bold; background-color:pink">Lastname</td> <td style="font:bold; background-color:pink">Firstname</td> <td style="font:bold; background-color:pink">State</td> </tr> </HeaderTemplate>
Notes re the repeater control EG-2 • The <% %> is the syntax for in liner server side code • The # is the binding expression • The Container object refers to the Repeater control • The DataItem method refers to a field in the current record <ItemTemplate> <tr> <td><%# Container.DataItem("au_lname") %></td> <td><%# Container.DataItem("au_fname") %></td> <td><%# Container.DataItem("state") %></td> </tr> </ItemTemplate>
Notes re the Calendar control EG-0 • Requirements • Calendar data is read from an XML file • See several events for one day • Title of the event to appear in the calendar; onclick display a detailed description • First day of the month should be Monday (rather than Sunday – default) • Weekends highlighted in a different colour
Notes re the Calendar control EG-1 • XML Source file format <MyCalendar> <Event> <ShortDesc>Gig in Portland - Jazz Club</ShortDesc> <DetailDesc>This should be fun - playing J & T again - be sure to bring the charts.</DetailDesc> <EventDate>2001/07/02</EventDate> <StartTime>6:00PM</StartTime> <EndTime>11:30PM</EndTime> </Event> <Event> <ShortDesc>Concert at the Riverfront</ShortDesc> <DetailDesc>4th of July celebration. Bring stand and a jacket.</DetailDesc> <EventDate>2001/07/04</EventDate> <StartTime>9:30PM</StartTime> <EndTime>11:00PM</EndTime> </Event>…… </MyCalendar>
Notes re the Calendar control EG-2 • MyCalendar.aspx • Calendar control defined within form tag and calendar properties set <form id="MyCalendarForm" method="post" runat="server"> <p align="center"> <asp:Calendar id="MyCalendar" runat="server" SelectedDate="2001/07/17" VisibleDate="2001/07/01" FirstDayOfWeek="Monday“ ……
Notes re the Calendar control EG-3 • Assign two event handlers for • OnDayRender • What should happen as each ‘day’ is being displayed in the calendar • OnSelectionChanged • What should happen when the user clicks on a day ……….. OnDayRender="MyCalendar_DayRender OnSelectionChanged="MyCalendar_SelectionChanged"> </asp:Calendar> • A label is created to show the selected date (used by MyCalendar_SelectionChanged)
Notes re the Calendar control EG-4 • A panel and repeater control are used to display the detailed descriptions of events for a day. Generated by the event proc. MyCalendar_SelectionChanged • The repeater control uses templates for output and will be bound to an arraylist of events. The repeater is within the panel; the panel will set the visibility <asp:panel id="DailyDetailsPanel" runat="server"> <asp:Repeater id="DailyEventDetailRepeater" runat="server"> <HeaderTemplate> …
Notes re the Calendar control EG-5 <td> <%# DataBinder.Eval(Container.DataItem, "ShortDesc") %> </td> The ASP.NET supplies a static method, called DataBinder.Eval, that evaluates late-bound data-binding expressions and optionally formats the result as a string. In the following code fragment, for example, an integer is displayed as a currency string. With the standard ASP.NET data-binding syntax, you must first cast the type of the data row in order to retrieve the data field, IntegerValue. Next, this is passed as an argument to the String.Format method: <%# String.Format("{0:c}", ((DataRowView)Container.DataItem)["IntegerValue"]) %> Contrast this syntax with that of DataBinder.Eval, which has only three arguments: the naming container for the data item, the data field name, and a format string. In a templated list like DataList Class, DataGrid Class, or Repeater Class, the naming container is always Container.DataItem. <%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:c}") %>
Notes re the Calendar control EG-6 Protected Function LoadMyCalendarData()As DataSet • Reads XML file and returns a dataset. • Called by Page_load , MyCalendar_DayRender and MyCalendar_SelectionChanged • Checks the session object to see if the dataset is cached (loaded before) Dim cachedDataSet as DataSet = Session("MyCalendarData") if ( Not cachedDataSet Is Nothing ) Then Return cachedDataSet End if • Dataset registered as a session • Session("MyCalendarData") = dataSet
Notes re the Calendar control EG-7 • MyCalendar_DayRender (raised each time a visible day is being rendered) sets • Background colour depending on weekday/end • Loops through the dataset checking the event date with the current date being rendered. A user defined public class (MyCalendarEventData) is used to hold the event information. This is allocated to a label control and added to the calendar control. • e.cell is the current cell • Dataset.Tables(0) is the first table in the tables collection for this dataset • Getsafedate() user defined function that checks that an event date from the XML file is valid
Notes re the Calendar control EG-8 Dim zRow as DataRow For Each zRow in dataSet.Tables(0).Rows Dim compareDate as DateTime compareDate = GetSafeDate ( zRow.Item("EventDate") ) If ( compareDate = e.Day.Date ) Then ' Event matches date criteria – display it... Dim myEventData as New MyCalendarEventData myEventData.ShortDesc = zRow.Item("ShortDesc") …… Dim dailyEventLabel as New Label dailyEventLabel.Text = "<br />" + myEventData.ShortDesc e.Cell.Controls.Add ( dailyEventLabel ) End if Next
Notes re the Calendar control EG-9 • ShowDailyEvents procedure • Display detailed information for the currently selected day • An arraylist is used to store the events for the that day Dim aEvents as new ArrayList() ….. aEvents.Add ( myEventData ) • Rendered by the repeater control under the calendar – bound to arraylist as the datasource DailyEventDetailRepeater.DataSource = aEvents DailyEventDetailRepeater.DataBind()
Notes re the EditTemplate EG-0 • Use the EditItem template to display different controls when the user selects ‘edit’ • DataGrid has properties for • EditCommand, UpdateCommand, CancelCommand, DeleteCommand <asp:DataGrid id="EventData AutoGenerateColumns="false" width="100%" runat="server" OnEditCommand="DEDR_Edit" OnUpdateCommand="DEDR_Update" OnCancelCommand="DEDR_Cancel" OnDeleteCommand="DEDR_Delete"> • AutoGenerateColumns=false so that columns may be manually defined by programmer (change column headings etc) • DEDR_Edit etc are user defined event handlers
Notes re the EditTemplate EG-1 • TemplateColumn • Represents a column type for the DataGrid control that allows you to customize the layout of controls in the column. • For each column, define a heading and then the items to be placed in the column. <asp:TemplateColumn HeaderText="Event"> <ItemTemplate> <%# Container.DataItem("ShortDesc") %> </ItemTemplate> <EditItemTemplate> <asp:TextBox id="txtShortDesc" Size="25" Text='<%# Container.DataItem("ShortDesc") %>' runat="server"/> </EditItemTemplate> </asp:TemplateColumn>
Notes re the EditTemplate EG-2 • The Heading is “EVENT” • <asp:TemplateColumn HeaderText="Event"> • The item is ‘the short desc’ <ItemTemplate> <%# Container.DataItem("ShortDesc") %> </ItemTemplate> • The edit item is a text box <EditItemTemplate> <asp:TextBox id="txtShortDesc" Size="25" Text='<%# Container.DataItem("ShortDesc") %>' runat="server"/> • Datagrid will automatically insert HTML tags (<tr> and <td>)
Notes re the EditTemplate EG-3 • The final column display the edit links <asp:TemplateColumn> <ItemTemplate> <asp:LinkButton CommandName="Edit" Text="Edit" runat="server"/> <asp:LinkButton CommandName="Delete" Text="Delete" runat="server"/> </ItemTemplate> <EditItemTemplate> <asp:LinkButton CommandName="Cancel" Text="Cancel" runat="server"/> <asp:LinkButton CommandName="Update" Text="Update" runat="server"/> </EditItemTemplate> </asp:TemplateColumn>
Notes re the EditTemplate EG-4 • The CommandName property identifies which command the link button is associated with <asp:LinkButton CommandName="Edit" Text="Edit" runat="server"/> • The button with CommandName=“Edit” will call the event procedure defined by OnEditCommand=“DEDR_Edit”
Notes re the EditTemplate EG-5 Sub DEDR_Edit(Sender As Object, E As DataGridCommandEventArgs) EventData.EditItemIndex =CInt(e.Item.ItemIndex) EventData.DataSource = LoadMyCalendarData EventData.DataBind() End Sub • Edit link puts grid into edit mode by setting the EditItemIndex property (to a number >0). • EditItemTemplate is then used • The index of the row (in the grid) is supplied by ASP.NET • Need to use the update command to then store the new data in the grid
Notes re the EditTemplate EG-6 Sub DEDR_Update(Sender As Object, E As DataGridCommandEventArgs) Dim dataSet As DataSet = LoadMyCalendarData Dim row As Integer = CInt(e.Item.ItemIndex) Dim EditText As TextBox EditText = E.Item.FindControl("txtShortDesc") dataSet.Tables(0).Rows(row).Item("ShortDesc") = EditText.Text EditText = E.Item.FindControl("txtDetailDesc") dataSet.Tables(0).Rows(row).Item("DetaiLDesc") = EditText.Text EditText = E.Item.FindControl("txtStartTime") dataSet.Tables(0).Rows(row).Item("StartTime") = EditText.Text EditText = E.Item.FindControl("txtEndTime") dataSet.Tables(0).Rows(row).Item("EndTime") = EditText.Text dataSet.WriteXml(Server.MapPath("MyCalendar.xml")) Session("MyCalendarData") = Nothing EventData.EditItemIndex = -1 EventData.DataSource = LoadMyCalendarData EventData.DataBind() End Sub
Notes re the EditTemplate EG-7 • FindControl is used to find the item in the grid as textbox name etc may be ambiguous within the grid. • Data is saved to the XML file dataSet.WriteXml(Server.MapPath("MyCalendar.xml")) Session("MyCalendarData") = Nothing • Grid is taken out of edit mode and data is reloaded EventData.EditItemIndex = -1 EventData.DataSource = LoadMyCalendarData EventData.DataBind()
Notes re the EditTemplate EG-8 • Cancel function • Take grid out of edit mode and reload data • Delete function • Use the index of the row to identify row to delete Dim dataSet As DataSet = LoadMyCalendarData Dim row As Integer = CInt(e.Item.ItemIndex) dataSet.Tables(0).Rows(row).Delete dataSet.WriteXml(Server.MapPath("MyCalendar.xml")) …..data is reloaded
Notes re the EditTemplate EG-9 • Adding new data • use the NewRow method to create a row object and the Add method to add the row to the table • The new row is put into edit mode using the row index Sub DEDR_Add(Sender As Object, E As EventArgs) Dim dataSet As DataSet = LoadMyCalendarData Dim newRow As DataRow newRow = dataSet.Tables(0).NewRow() newRow.Item("EventDate") = "15/07/2001“ ….. newRow.Item("EndTime") = "" dataSet.Tables(0).Rows.Add(newRow) EventData.EditItemIndex = EventData.Items.Count - 1 EventData.DataSource = LoadMyCalendarData EventData.DataBind() End Sub