16.8 Using the DataList Web Control

 <  Day Day Up  >  

16.8 Using the DataList Web Control

You want to display a formatted repeating list of data that is extracted from a database.


Technique

You use the DataList control to display data from a database using a series of templates that control how each item should be displayed. You can define styles to delineate individual items. The DataList also supports the ability for a user to select an item in the list as well as the ability to edit the item. This functionality, however, does not come for free and must be enabled by the developer. To begin creating a DataList control that is data-bound to values from a SQL database table, drag and drop a DataList control onto the Web Form and create the SqlConnection , an SqlDataAdapter , and a DataSet . Within the Page_Load event, add the code to fill the DataSet and databind the page controls if the loading is not the result of a post-back event:

 
 private void Page_Load(object sender, System.EventArgs e) {     if( !Page.IsPostBack )     {         sqlDataAdapter1.Fill( productsDS1 );         DataBind();     } } 

There are three item templates for a DataList control. These templates appear based on the current state of each individual item that is placed into the DataList . The ItemTemplate and AlternatingItemTemplate display each item in succession for items that are not selected or not currently being edited. If no AlternatingItemTemplate is specified, the SelectedItemTemplate is used instead. The SelectedItemTemplate formats the item that the user has selected. The EditItemTemplate formats an item that is being edited.

To specify the format of any of the templates, right-click on the DataList control and select Edit Templates, Item Templates. Drag and drop controls from the toolbox into the template recipe being edited. The DataList control itself is bound to a DataSet , but no data from the DataSet is displayed unless a control within the template is bound to the data. To do this step, select the control that you want to databind from within the template and open the DataBindings property. In the DataBindings dialog, select the Text property as the property to bind and then expand the Container tree within the available bindings. Select the appropriate column name from the DataItem collection.

You can associate commands within the DataList to control selection and the ability to edit and update an individual item. These commands associate server-side controls with special keywords indicating the DataList command to take. For instance, within an ItemTemplate , you can create a LinkButton whose CommandText property is set to select . Once the user clicks this link button, a corresponding ItemCommand event is fired . Within the event handler for this method, set the SelectedItemIndex property of the DataList to the item that was clicked on and rebind the DataList to make the formatting changes. In the following example, a DataList control displays the name of each product in the Northwind database Products table. The name of each product is also a LinkButton whose CommandText property is set to select . When the user clicks on the name of the product, the selected index changes and the SelectedItemTemplate for that item is used. In the same manner, the SelectedItemTemplate contains a LinkButton that will place the item into edit mode by setting the CommandText property of the LinkButton to edit and changing the EditItemIndex of the DataList within the event handler for the EditItem event, as shown in Listing 16.4.

Listing 16.4 Creating DataList Commands
 <asp:DataList id="DataList1" runat="server" BorderColor="#999999"     BorderStyle="None" BackColor="White" CellPadding="3" GridLines="Vertical"     BorderWidth="1px" DataSource="<%# productsDS1 %>" DataKeyField="ProductID"     DataMember="Products" Width="648px" CellSpacing="5">     <!-- DataList Styles -->     <ItemStyle ForeColor="Black" BackColor="#EEEEEE"></ItemStyle>     <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#CCCCFF"/>     <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle>     <SeparatorStyle BorderStyle="Solid"></SeparatorStyle>     <FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle>     <HeaderStyle Font-Bold="True" HorizontalAlign="Center" ForeColor="White" graphics/ccc.gif BackColor="#000084"></HeaderStyle>     <!-- DataList Templates -->     <HeaderTemplate>Products</HeaderTemplate>     <SelectedItemTemplate>     <P><FONT color="#000000">         <%# DataBinder.Eval(Container.DataItem, "ProductName") %>         <asp:LinkButton id="btnRename" Runat="server"             CommandName="edit" Text="Rename"/>         <BR>         ID: <%# DataBinder.Eval(Container.DataItem, "UnitPrice") %> <BR>         Price: <%# DataBinder.Eval(Container.DataItem, "UnitPrice") %> <BR>     </FONT></P>     </SelectedItemTemplate>     <ItemTemplate>         <asp:LinkButton id=LinkButton1 Runat="server" CommandName="select"             Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>'/>     </ItemTemplate>     <EditItemTemplate>         <asp:TextBox id="tbRename" runat="server" Width="294px"             Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>'/>         <asp:LinkButton id="btnUpdate" Runat="server" CommandName="update"             Text="Update"></asp:LinkButton><BR>     </EditItemTemplate> </asp:DataList> 

Listing 16.5 shows the relevant code from the code-behind file for Listing 16.4.

Listing 16.5 Handling DataList Command Events
 // event handler when an item is selected private void DataList1_ItemCommand_1(object source,     System.Web.UI.WebControls.DataListCommandEventArgs e) {     DataList1.SelectedIndex = e.Item.ItemIndex;     sqlDataAdapter1.Fill( productsDS1 );     DataBind(); } // event handler when user wants to edit an item private void DataList1_EditCommand(object source,     System.Web.UI.WebControls.DataListCommandEventArgs e) {     DataList1.EditItemIndex = e.Item.ItemIndex;     sqlDataAdapter1.Fill( productsDS1 );     DataBind(); } 

The EditItemTemplate in the Web Form code just shown contains a LinkButton for the update command. Just as the other commands do, clicking this button fires an event, which in this case is named UpdateCommand . It is within this event handler that you update the database and return the DataList item being edited into selection mode. The update event handler for the DataList shown earlier performs the steps just mentioned. One thing to note is the use of the DataKeys property defined in the DataList . You initially set this property by specifying the column name within the database table that is used as a key value for each row. For the Products table, the column name is the ProductID . When the list is data-bound, each item within the DataList has a corresponding key within the DataKeys collection, enabling you to make a two-way association between the DataList and database table.

Listing 16.6 Updating a Database Using DataList Commands
 private void DataList1_UpdateCommand(object source,     System.Web.UI.WebControls.DataListCommandEventArgs e) {     // stop editing and select item     DataList1.EditItemIndex = -1;     DataList1.SelectedIndex = e.Item.ItemIndex;     // update database     ProductsDS.ProductsRow row =         productsDS1.Products.FindByProductID(             (int)DataList1.DataKeys[e.Item.ItemIndex]);     row["ProductName"] = ((TextBox)e.Item.FindControl("tbRename")).Text;     sqlDataAdapter1.Update( productsDS1 );     DataBind(); } 

Comments

The DataList control is one of the functionally richest controls in ASP.NET. By utilizing a template approach to render data based on the state of each individual item, you can really begin to see why the Web page of yesterday is being called the Web application of today. For most intents and purposes, the example shown earlier really is an application presented within a Web browser because it allows full editing and interaction by a user.

Although the DataList control is a full-featured control allowing great flexibility, it is missing a few features that another control, the DataGrid , addresses. The most prominent feature is pagination, which is covered in the next recipe. The DataList renders all data from a table, and if the table itself is large, the data consumes a lot of virtual real estate within the browser. In other words, a table with a lot of rows generates a large DataList , which might be confusing to a user. Pagination allows you to render a set number of items with links to subsequent pages for the rest of the data. For large data sets, the DataGrid might be better suited to display the data, but if your goal is to simply render small datasets, then the DataList might be a better fit.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net