Sie sind auf Seite 1von 16

ASP.NET 2.

0 DataList Control 

 
ASP.NET 2.0 DataList Control 
 

Description ....................................................................................................................................................................2 
Step by step – Create a DataList Control to display data ..............................................................................................4  
Step by step – Create a DataList Control with editing enabled.....................................................................................9  
Default CommandName Events ..............................................................................................................................11 
Databinding the DataList Control to a Datasource......................................................................................................11  
Postbacks.....................................................................................................................................................................12 
DataList Control Events & Database Operations .........................................................................................................13  
Event – EditCommand .............................................................................................................................................13 
Event – CancelCommand.........................................................................................................................................13 
Event – UpdateCommand........................................................................................................................................14 
Event – DeleteCommand.........................................................................................................................................14 
Event – ItemCommand ............................................................................................................................................15 
DataList Control Quick Start ........................................................................................................................................16 

Page | 1 
 
ASP.NET 2.0 DataList Control 

Description 
See msdn.com for more info: 
http://msdn2.microsoft.com/en‐us/library/system.web.ui.webcontrols.datalist.aspx 

The DataList Control belongs to the System.Web.UI.WebControls Namespace. 

 
DataList Control 
 

 
 
Above: Runtime view of the rendered DataList Control. This DataList Control has been formatted using HTML tables. 
 
 

The DataList Control is a repeating control which displays displays the values of a DataSource using
templates. Each template area allows for the addition of regular tools and may be formatted using html.

The following table lists the supported templates.

Template Name Description

AlternatingItemTemplate   If defined, provides the content and layout for alternating items in the
DataList. If not defined, ItemTemplate is used.

EditItemTemplate If defined, provides the content and layout for the item currently being edited
in the DataList. If not defined, ItemTemplate is used.

Page | 2 
 
ASP.NET 2.0 DataList Control 

FooterTemplate If defined, provides the content and layout for the footer section of the
DataList. If not defined, a footer section will not be displayed.

HeaderTemplate If defined, provides the content and layout for the header section of the
DataList. If not defined, a header section will not be displayed.

ItemTemplate Required template that provides the content and layout for items in the
DataList.

SelectedItemTemplate If defined, provides the content and layout for the currently selected item in
the DataList. If not defined, ItemTemplate is used.

SeperatorTemplate If defined, provides the content and layout for the separator between items in
the DataList. If not defined, a separator will not be displayed.

At the very minimum, the ItemTemplate needs to be defined to display the items in the DataList control.

The DataList control also allows you to select, sort, and edit records via DataList Control events.

Locate the events belonging to the DataList Control by switching to Code view and then selecting the name
of your DataList Control from the Class Name drop down list (left). Then click the arrow on the Method
Name drop down list (right).

DataList Control events

Above: DataList Control events Method Name list. 

Page | 3 
 
ASP.NET 2.0 DataList Control 

Above: Larger view of DataList Control events as seen in the DataList Control Method Name list.

Step by step – Create a DataList Control to display data 
Before you begin, it is helpful to plan how you wish the DataList to look and behave. A simple sketch or wireframe 
may be used to assist in planning. 

1. Using your sketch as a guide, create a HTML table on your Web Form. 

 
<table border="0"> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
            <tr> 
                <td align="right" valign="top"> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
        </table> 

Page | 4 
 
ASP.NET 2.0 DataList Control 

 
Above: Example HTML code for a table. 
 

2. Place the required controls in the desired areas of the table, making sure to name each control. 

 
 
Above: Design view of the HTML table including 2 LinkButtons, 1 ImageButton and a Label. 
 
<table border="0"> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                    <asp:LinkButton ID="lnkProdName" runat="server">LinkButton</asp:LinkButton> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                    <asp:ImageButton ID="imgbtnProd" runat="server" /> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                    <asp:Label ID="lblPrice" runat="server" Text="Label"></asp:Label> 
            </tr> 
            <tr> 
                <td align="right" valign="top"> 
                    <asp:LinkButton ID="lnkMore" runat="server">LinkButton</asp:LinkButton> 
                </td> 
            </tr> 
            <tr> 
                <td align="left" valign="top"> 
                </td> 
            </tr> 
        </table> 
 
Above: Example HTML code for the table containing controls. 
 
 

3. Locate a DataList Control in the Data section of the Visual Studio Toolbox. Place onto the desired area of your 
Web Form. 

Page | 5 
 
ASP.NET 2.0 DataList Control 

4. With the DataList Control selected, locate the Properties pane and name the DataList Control (ID property). 

5. Switch to Source View to locate the DataList Source code. Locate the opening and closing tags of the
DataList Control and type opening and closing ItemTemplate tags. This will create a container to hold the
HTML table you created earlier.

 
<asp:DataList ID="dtlProducts" runat="server"> 
            <ItemTemplate> 
            </ItemTemplate> 
 </asp:DataList> 

Above: Example DataList Source code with an ItemTemplate area added.

6. Locate the Table code you created earlier and copy/cut it into the ItemTemplate area of the DataList
Control.

<asp:DataList ID="dtlProducts" runat="server"> 
            <ItemTemplate> 
                <table border="0"> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:LinkButton ID="lnkProdName" runat="server">LinkButton</asp:LinkButton> 
                        </td> 
                    </tr> 

Page | 6 
 
ASP.NET 2.0 DataList Control 

 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:ImageButton ID="imgbtnProd" runat="server" /> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:Label ID="lblPrice" runat="server" Text="Label"></asp:Label> 
                    </tr> 
                    <tr> 
                        <td align="right" valign="top"> 
                            <asp:LinkButton ID="lnkMore" runat="server">LinkButton</asp:LinkButton> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                </table> 
            </ItemTemplate> 
        </asp:DataList> 

Above: DataList Control Source code with the Table code added to the ItemTemplate area. 

7. Switch to Design view and notice that the DataList Control shows a preview of how the control will look
at runtime. Locate the Smart Tag (small arrow) at the top right corner of the control & click to open the
DataList Tasks menu. From the menu select Edit Templates.

8. From the Display drop down list, select the ItemTemplates. Notice the ItemTemplate area contains the HTML 
table from the previous steps. 

Page | 7 
 
ASP.NET 2.0 DataList Control 

9. Locate the Smart Tag (small arrow) for each control within the DataList Control & click to open its Tasks
menu to format and data bind each control to the DataSource.

Page | 8 
 
ASP.NET 2.0 DataList Control 

Step by step – Create a DataList Control with editing 
enabled 
The DataList Control provides support for an EditItemTemplate. Items in the DataList Control are selected via 
controls which have a CommandName property. When a control with a CommandName is clicked, a 
corresponding DataList event fires. 

For these steps, use either the DataList tasks menu or simply switch to Source view and hand code as required. 

In this example we will assume that it is the Product Name which will have editing enabled. 

1.  Place a LinkButton in the ItemTemplate of the DataList. Locate the CommandName property and called it Edit. 
Notice that the one in this example (lnkEdit) has a CommandName called Edit .  

2. Switch to Source view and type opening and closing EditItemTemplate tags immediately below the closing  
ItemTemplate tag. 

 
<asp:DataList ID="dtlProducts" runat="server"> 
            <ItemTemplate> 
                <table border="0"> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:LinkButton ID="lnkProdName" CommandName="More" Text='<%#Eval("ProductName")%>' 
                                CssClass="xxx" runat="server" /> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:ImageButton ID="imgbtnProd" BorderWidth="1px" CssClass="bord" Width="100px" 
                                Height="100px" ImageUrl='<%# Eval("ProductID", "productimages/{0}.jpg") %>' CommandName="More" 
                                runat="server" /> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:Label ID="lblPrice" runat="server" CssClass="Item" Text='<%#Eval("Price","{0:c}") %>'></asp:Label></td> 
                    </tr> 
                    <tr> 
                        <td align="right" valign="top"> 
                            <asp:LinkButton ID="lnkEdit" CommandName="Edit" runat="server">Edit </asp:LinkButton> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                </table> 
            </ItemTemplate> 
            <EditItemTemplate> 
            </EditItemTemplate> 
        </asp:DataList> 
 
Above: Example Source code of the DataList Control with an Edit LinkButton (lnkEdit) added to the ItemTemplate and empty EditItemTemplate 

Page | 9 
 
ASP.NET 2.0 DataList Control 

 
added. 
 
 

3. To ensure consistency across both templates, copy the table code from the ItemTemplate.  

4. Paste this table code into the EditItemTemplate. 

5. In the EditItemTemplate, the LinkButton (lnkProductName) will be replaced by a textbox called 
txtEditProductName. It will be bound to the ProductName field. 

6. Still in the EditItemTemplate, remove the Edit LinkButton and place an Update LinkButton (lnkUpdate, 
CommandName=”Update”) and a Cancel LinkButton (lnkCancel, CommandName=”Cancel”) in its place. 

 
<asp:DataList ID="dtlProducts" runat="server"> 
            <ItemTemplate> 
                <table border="0"> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:LinkButton ID="lnkProdName" CommandName="More" Text='<%#Eval("ProductName")%>' 
                                CssClass="xxx" runat="server" /> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:ImageButton ID="imgbtnProd" BorderWidth="1px" CssClass="bord" Width="100px" 
                                Height="100px" ImageUrl='<%# Eval("ProductID", "productimages/{0}.jpg") %>' CommandName="More" 
                                runat="server" /> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:Label ID="lblPrice" runat="server" CssClass="Item" Text='<%#Eval("Price","{0:c}") %>'></asp:Label></td> 
                    </tr> 
                    <tr> 
                        <td align="right" valign="top"> 
                              <asp:LinkButton ID="lnkEdit" CommandName="Edit" runat="server">Edit </asp:LinkButton> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                </table> 
            </ItemTemplate> 
 
            <EditItemTemplate> 
                <table border="0"> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:TextBox ID="txtEditProductName" Text='<%#Eval("ProductName")%>' runat="server"></asp:TextBox> 
                            CssClass="xxx" runat="server" /> 
                        </td> 

Page | 10 
 
ASP.NET 2.0 DataList Control 

 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:ImageButton ID="imgbtnProd" BorderWidth="1px" CssClass="bord" Width="100px" 
                                Height="100px" ImageUrl='<%# Eval("ProductID", "productimages/{0}.jpg") %>' CommandName="More" 
                                runat="server" /> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                            <asp:Label ID="lblPrice" runat="server" CssClass="Item" Text='<%#Eval("Price","{0:c}") %>'></asp:Label></td> 
                    </tr> 
                    <tr> 
                        <td align="right" valign="top"> 
                            <asp:LinkButton ID="lnkUpdate" CommandName="Update" runat="server">Update </asp:LinkButton> 
                            <asp:LinkButton ID="lnkCancel" CommandName="Cancel" runat="server">Cancel </asp:LinkButton> 
                        </td> 
                    </tr> 
                    <tr> 
                        <td align="left" valign="top"> 
                        </td> 
                    </tr> 
                </table> 
            </EditItemTemplate> 
        </asp:DataList> 
 
Above: Example DataList Source code with a populated EditItemTemplate. 
 
 

7. Locate the events corresponding with the CommandNames set inside the DataList and code. 

Default CommandName Events 
 
By default, the following CommandNames will fire these corresponding DataList events: 

CommandName:  Corresponding event: 
Edit  EditCommand 
Cancel  CancelCommand 
Update  UpdateCommand 
Delete  DeleteCommand 
 
 

Databinding the DataList Control to a Datasource 
It is helpful to create a custom routine to handle populating/refreshing controls such as the DataList Control. As 
this control will need to be refreshed many times, this reusable component keeps the code that performs the 
desired SELECT operation so that the routine may be called simply by name when required. 

As well as the SELECT operation code, you will need to add the code responsible for performing the actual 
databinding of the results to the DataList Control. 

Page | 11 
 
ASP.NET 2.0 DataList Control 

Create a procedure / event with a short meaningful name such as RefreshDataList and within it: 

• The first task is to perform the SELECT operation 
• The second task is databind the results of the SELECT to the DataList Control. 
 
ƒ DataList Control Databinding properties and attributes: 

DataSource ‐ The name of the Dataset 
DataMember  ‐ The name of the Query within the Dataset 
DataKeyField ‐  The field that contains the ID for each record. 
DataBind – Go! 

Examine the code below: 

 
Protected Sub RefreshDataList() 
 
‘ Step 1. 
' SELECT database operation goes here......... 
 ‘ ………………………………………………………………… 
‘ ………………………………………………………………….. 
 
 
‘ Step 2. 
‘ Databind the DataList to the results of the SELECT query. 
 
        Me.dtlUsers.DataSource = dsResults 
        Me.dtlUsers.DataMember = "GetProductsQuery" 
        Me.dtlUsers.DataKeyField = "ProductID" 
        Me.dtlUsers.DataBind() 
 
    End Sub
 
 
 

Postbacks 
Watch out for Page Postbacks!!! The load event should only run the refresh code if the page is loading for the first 
time. 

Use Page.IsPostBack to check whether the page is being loaded in response to a client postback, or if it is being 
loaded and accessed for the first time. 

 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
 
        If Not Page.IsPostBack Then 
            RefreshDataList() 
        End If 
 
    End Sub 
 

Page | 12 
 
ASP.NET 2.0 DataList Control 

DataList Control Events & Database Operations 
When performing Operations with the DataList Control, the code is contained within the events of the  DataList 
Control. 

It is important to remember that any time an event fires, the final line of code should refresh the DataList Control.  

Event – EditCommand 
The following shows the EditCommand event and sample code. This event fires when a control with a 
CommandName of Edit is clicked and executes code which opens any EditItemTemplates within the selected item. 

• The first task is to put the DataList Control into Edit Mode. 
• The second task is to refresh the DataList Control. 

Examine the code below: 

 
Protected Sub dtlUsers_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles 
dtlUsers.EditCommand 
 
‘ Step 1. 
‘ Put the DataList into Edit Mode for the selected item.     
 Me.dtlUsers.EditItemIndex = e.Item.ItemIndex 
 
‘ Step 2. 
‘ Call the sub to Refresh the DataList. 
 RefreshDataList() 
 
 End Sub 
 
 

Event – CancelCommand 
The following shows the CancelCommand event and sample code. This event fires when a control with a 
CommandName of Cancel is clicked and executes code which closes any open EditItemTemplates within the 
selected item. 

• The first task is to take the DataList Control out of Edit Mode. 
• The second task is to refresh the DataList Control. 

Examine the code below: 

 
Protected Sub dtlUsers_CancelCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) 
Handles dtlUsers.CancelCommand 
 
‘ Step 1. 
‘ Take the DataList out of Edit Mode.             
Me.dtlUsers.EditItemIndex = ‐1 
 
‘ Step 2. 

Page | 13 
 
ASP.NET 2.0 DataList Control 

 
‘ Call the sub to Refresh the DataList. 
RefreshDataList() 
 
 End Sub 
 
 

Event – UpdateCommand 
 
The following shows the UpdateCommand event and sample code. This event fires when a control with a 
CommandName of Upadte is clicked and executes code on the selected item. 

• The first task is to harvest the record ID of the item to be updated. In this example, an Integer variable 
called intEditItemID is created to hold this value. This value will be used to UPDATE the correct record. 
• The second task is to declare each control in the EditItemTemplate of the DataList Control so that the 
entered text or other value can be accessed. 
• The third task is the UPDATE operation. 
• The fourth task is to take the DataList Control out of Edit Mode. 
• The fifth task is to refresh the DataList Control to reflect the changes. 

Examine the code below: 

 
Protected Sub dtlUsers_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) 
Handles dtlUsers.UpdateCommand 
 
‘ Step 1. 
‘ Get ID of record selected.       
Dim EditItemID As Integer = Me.dtlUsers.DataKeys(e.Item.ItemIndex) 
 
‘ Step 2. 
‘ Declare each control in the EditItemTemplate. 
Dim txtEditFirstName As TextBox = CType(e.Item.FindControl("txtEditFirstName"), TextBox) 
Dim txtEditLastName As TextBox = CType(e.Item.FindControl("txtEditLastName"), TextBox) 
 
‘ Step 3. 
' UPDATE Database Operation code goes here.... 
‘ ……………………………………………………………………….. 
‘ ………………………………………………………………………. 
 
‘ Step 4. 
‘ Take the DataList out of Edit Mode. 
Me.dtlUsers.EditItemIndex = ‐1 
 
‘ Step 5. 
‘ Call the sub to Refresh the DataList 
Me.RefreshDataList() 
 
End Sub 
 
 

Event – DeleteCommand 
 
The following shows the DeleteCommand event and sample code. This event fires when a control with a 
CommandName of Delete is clicked and executes code on the selected item. 

Page | 14 
 
ASP.NET 2.0 DataList Control 

The first line of code creates an Integer variable called intSelectedID to hold the ID of the record in the row to be 
deleted. This value will be used to DELETE the correct record. 

• The first task is to harvest the record ID of the item to be deleted. In this example, an Integer variable 
called intSelectedID is created to hold this value. This value will be used to DELETE the correct record. 
• The second task is the DELETE operation. 
• The third task is to refresh the DataList Control to reflect the changes. 

Examine the code below: 

 
Protected Sub dtlUsers_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) 
Handles dtlUsers.DeleteCommand 
 
‘ Step 1. 
‘ Get ID of record selected.       
Dim intSelectedID As Integer = Me.dtlUsers.DataKeys(e.Item.ItemIndex) 
 
‘ Step 2. 
' DELETE Database Operation code goes here.... 
‘ ……………………………………………………………………….. 
‘ ………………………………………………………………………. 
 
‘ Step 3. 
‘ Call the sub to Refresh the DataList. 
 RefreshDataList() 
 
End Sub 
 
 

Event – ItemCommand 
 
The following shows the ItemCommand event and sample code. This event fires when a control containing a 
CommandName is clicked and executes code for the appropriate Command on the selected item. 

To create an event for your own custom CommandName, use the DataList ItemCommand event. 

Examine the code below: 

 
Protected Sub dtlUsers_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles 
dtlUsers.ItemCommand 
 
' Get the record ID of the item for which the command will execute. 
Dim intSelectedID As Integer = Me.dtlUsers.DataKeys(e.Item.ItemIndex) 
 
' If the CommandName of the control in theitem = "DoSomething". 
        If e.CommandName = "DoSomething" Then 
                ‘ Code…… 
        End If 
 
' If the CommandName of the control in theitem = "GoHere". 
        If e.CommandName = "GoHere" Then 
                ‘ Code…… 
        End If 
 
    End Sub 

Page | 15 
 
ASP.NET 2.0 DataList Control 

 
 
 

DataList Control Quick Start 
1. Place a DataList onto your Web Form. 

2. Paste the source code containing formatting and controls into the ItemTemplate.  

3. Set the display and behaviour properties for each control. 

3. Bind Database results to the GridView Control. 

If the contents of the DataList Controlo are to be editable: 

4. Place a control with a CommandName property in the ItemTemplate. 

5.  Create an EditItemTemplate beneath the ItemTemplate in the DataList. 

6. Place the appropriate controls in the EditItemTemplate containing CommandNames 

Page | 16 
 

Das könnte Ihnen auch gefallen