Similar to the FormView, the DataList control's rendered output depends upon templates rather than BoundFields, CheckBoxFields, and so on. Unlike the FormView, the DataList is designed to display a set of records rather than a solitary one.
If we need to display multiple records from a data source we can use the GridView, the DataList or the Repeater control.
While the GridView makes it a snap to display, page through, sort, edit, and delete data, its appearance is a bit boxy (renders a row for each record in the data source, displaying the record s data fields in columns): The markup responsible for the GridView s structure is fixed it includes an HTML <table> with a table row (<tr>) for each record and a table cell (<td>) for each field.
To provide a greater degree of customization in the appearance and rendered markup when displaying multiple records, ASP.NET offers the DataList and Repeater controls. The DataList and Repeater controls render their content using templates rather than BoundFields, CheckBoxFields, ButtonFields, and so on.
Like the GridView, the DataList renders as an HTML <table>, but allows for multiple data source records to be displayed per table row. The Repeater, on the other hand, renders no additional markup than what you explicitly specify, and is an ideal candidate when you need precise control over the markup emitted.
Notes:
- The DataList does not support two-way databinding [4];
- The DataList has a number of properties that are required for the updating and deleting process, and these values are stored in view state. Therefore, when building a DataList that supports editing or deleting data, it is essential that the DataList's view state be enabled [4].
DataList Properties [3]:
The DataList, by default, lists its items in a single-column, multi-row table, which mimics the layout of a GridView with a single TemplateField. While this default layout is acceptable, we can maximize screen real estate by displaying multiple data source items per row. Accomplishing this is simply a matter of setting the: RepeatColumnsproperty to the number of columns to display per row;RepeatDirectionproperty can be used to indicate whether the contents of the multi-column, multi-row table should be laid out horizontally from left to right, top to bottom or vertically from top to bottom, left to right;- DataKeyField property [4] when updating or deleting, we need to be able to uniquely identify each item in the DataList. Set this property to the primary key field of the displayed data. Doing so will populate the DataList s DataKeys collection with the specified DataKeyField value for each DataList item.
DataList Templates [2]:
When binding a data source to a FormView control through the FormView s smart tag, Visual Studio created anItemTemplate, InsertItemTemplate, and EditItemTemplate. With the DataList, however, only an ItemTemplate is created. This is because the DataList does not have the same built-in editing and inserting support offered by the FormView. The DataList does contain edit- and delete-related events, and editing and deleting support can be added with a bit of code, but there s no simple out-of-the-box support as with the FormView.In addition to the
ItemTemplate, the DataList supports six other optional templates:HeaderTemplateif provided, adds a header row to the output and is used to render this row;AlternatingItemTemplateused to render alternating items;SelectedItemTemplateused to render the selected item; the selected item is the item whose index corresponds to the DataList sSelectedIndexproperty;EditItemTemplateused to render the item being edited;SeparatorTemplateif provided, adds a separator between each item and is used to render this separator;FooterTemplate- if provided, adds a footer row to the output and is used to render this row;
<asp:DataList ID="DataList1" runat="server" DataKeyField="ProductID"
DataSourceID="ObjectDataSource1">
<SeparatorTemplate> <hr />
</SeparatorTemplate>
<HeaderTemplate>
<h3>Product Information</h3>
</HeaderTemplate>
<ItemTemplate>
<h4><asp:Label ID="ProductNameLabel" runat="server"
Text='<%# Eval("ProductName") %>' /></h4>
<table>
<tr>
<td class="ProductPropertyLabel">CategoryName:</td>
<td><asp:Label ID="CategoryNameLabel" runat="server"
Text='<%# Eval("CategoryName") %>' /></td>
<td class="ProductPropertyLabel">SupplierName:</td>
<td><asp:Label ID="SupplierNameLabel" runat="server"
Text='<%# Eval("SupplierName") %>' /></td>
</tr>
<tr>
<td class="ProductPropertyLabel">Qty/Unit:</td>
<td><asp:Label ID="QuantityPerUnitLabel" runat="server"
Text='<%# Eval("QuantityPerUnit") %>' /></td>
<td class="ProductPropertyLabel">Price:</td>
<td><asp:Label ID="UnitPriceLabel" runat="server"
Text='<%# Eval("UnitPrice") %>' /></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>DataList Events [2]:
When data is bound to a DataList, either from a data source control or through programmatically assigning data to the control sDataSource property and calling its DataBind() method, the DataList s DataBinding event fires, the data source enumerated, and each data record is bound to the DataList. For each record in the data source, the DataList creates a DataListItem object that is then bound to the current record. During this process, the DataList raises two events:ItemCreatedfires after theDataListItemhas been createdItemDataBoundfires after the current record has been bound to theDataListItem
The following steps outline the data binding process for the DataList control.
- The DataList s
DataBindingevent fires - The data is bound to the DataList
For each record in the data source
a. Create aDataListItemobject
b. Fire theItemCreatedevent
c. Bind the record to theDataListItem
d. Fire theItemDataBoundevent
f. Add theDataListItemto theItemscollection
-
ItemCommand[4] this event is raised when a Button, LinkButton, or ImageButton that has itsCommandNameproperty set, is clicked from within a Repeater or DataList. For the DataList, if theCommandNameproperty is set to a certain value, an additional event may be raised as well. This specialCommandNameproperty values include, among others:
- "Cancel" raises theCancelCommandevent;
- "Edit" raises theEditCommandevent;
- "Update" raises theUpdateCommandevent).
Although this special events will be raised if theCommandNamehas this special values, theItemCommandevent will still be raised with them. So we can ignore this special events and treat everything inside theItemCommandevent if we prefer.(remember: these events are raised in addition to theItemCommandevent)
aspx file:
<asp:DataList ID="ProductsDataList" runat="server"
DataKeyField="ProductID"
DataSourceID="ProductsObjectDataSource"
RepeatColumns="2"
OnItemCommand="ProductsDataList_ItemCommand">
<ItemTemplate>
<h5>
<asp:Label ID="ProductNameLabel" runat="server"
Text='<%# Eval("ProductName") %>' />
</h5>
Price:
<asp:Label ID="UnitPriceLabel" runat="server"
Text='<%# Eval("UnitPrice","{0:C}") %>' />
<br />
<asp:Button ID="EditButton" runat="server"
CommandName="Edit"
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server"
CommandName="Delete"
Text="Delete"
OnClientClick='return confirm("Eliminar?");' />
</ItemTemplate>
<EditItemTemplate>
Product:<asp:TextBox ID="ProductNameTextBox" runat="server"
Text='<%# Eval("ProductName") %>' />
<br />
Price:<asp:TextBox ID="UnitPriceTextBox" runat="server"
Text='<%# Eval("UnitPrice", "{0:C}") %>' />
<br />
<asp:Button ID="UpdateButton" runat="server"
CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server"
CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:DataList>cs file(s). We have two options here, use only the Datalist ItemCommand for every button clicked inside the Datalist, or since they have the special names set ("Edit", "Cancel", "Delete" and "Update") we can use the special events that each of them raises.
protected void ProductsDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
ProductsDataList.EditItemIndex = e.Item.ItemIndex;
ProductsDataList.DataBind();
}
else if (e.CommandName == "Cancel")
returnToReadMode();
else if (e.CommandName == "Update")
{
int productID = Convert.ToInt32(ProductsDataList.DataKeys[e.Item.ItemIndex]);
TextBox nameTextBox = (TextBox)e.Item.FindControl("ProductNameTextBox");
TextBox priceTextBox = (TextBox)e.Item.FindControl("UnitPriceTextBox");
string productName = null;
if (!String.IsNullOrEmpty(nameTextBox.Text.Trim()))
productName = nameTextBox.Text.Trim();
decimal? productPrice = null;
if(!String.IsNullOrEmpty(priceTextBox.Text.Trim()))
productPrice = decimal.Parse(priceTextBox.Text.Replace('.',',').Trim(),
System.Globalization.NumberStyles.Currency);
//ProductsBLL productsAPI = new ProductsBLL();
ProductsAPI.UpdateProduct(productID, productName, productPrice);
returnToReadMode();
}
else if (e.CommandName == "Delete")
{
int productID = (int)ProductsDataList.DataKeys[e.Item.ItemIndex];
ProductsAPI.DeleteProduct(productID);
returnToReadMode();
}
}
protected void returnToReadMode()
{
ProductsDataList.EditItemIndex = -1;
ProductsDataList.DataBind();
}or we could use the special events raised:
protected void ProductsDataList_CancelCommand(object source, DataListCommandEventArgs e){}
protected void ProductsDataList_UpdateCommand(object source, DataListCommandEventArgs e){}
protected void ProductsDataList_DeleteCommand(object source, DataListCommandEventArgs e){}
protected void ProductsDataList_EditCommand(object source, DataListCommandEventArgs e){}to use them we would need to connect them to the Datalist:
<asp:DataList ID="ProductsDataList" runat="server"
DataKeyField="ProductID"
DataSourceID="ProductsObjectDataSource"
RepeatColumns="2"
OnItemCommand="ProductsDataList_ItemCommand"
OnCancelCommand="ProductsDataList_CancelCommand"
OnEditCommand="ProductsDataList_EditCommand"
OnUpdateCommand="ProductsDataList_UpdateCommand"
OnDeleteCommand="ProductsDataList_DeleteCommand"> Related articles:
[1] - DataList Class (.NET Class Library)
[2] - Displaying Data with the DataList and Repeater Controls
[3] - Showing Multiple Records per Row with the DataList Control
[4] - An Overview of Editing and Deleting Data in the DataList
No comments:
Post a Comment