AddThis Social Bookmark Button

Print

ASP.NET Data Controls Part 3: DataList

by Wei-Meng Lee
03/10/2003

In this third part of the ASP.NET Data Controls series, I will talk about the DataList control. The DataList control is somewhat a combination of the DataGrid and Repeater controls. It works like the Repeater control, allowing you to create templates so that it can be bound to a data source. It also allows you to edit records, much like the DataGrid control.

Using the DataList Control

To use the DataList control, drag and drop the DataList control from the Toolbox in Visual Studio .NET.

You can specify the formatting of the DataList control by right-clicking on the control and selecting Properties. In the Properties window, click on the Auto Format... link at the bottom:

Formatting the DataList control
Figure 1. Formatting the DataList control

Choose the color scheme that you like. When you are done, switch to HTML view mode. You should see something like this:


<asp:DataList id="DataList1" 
   style="Z-INDEX: 101; 
     LEFT: 16px; 
     POSITION: absolute; 
     TOP: 16px" 
   runat="server"
   BorderColor="#DEBA84" BorderStyle="None" 
   CellSpacing="2" BackColor="#DEBA84" 
   CellPadding="3" GridLines="Both" BorderWidth="1px">

   <SelectedItemStyle Font-Bold="True" ForeColor="White"
       BackColor="#738A9C">
   </SelectedItemStyle>

   <ItemStyle ForeColor="#8C4510" BackColor="#FFF7E7">
   </ItemStyle>

   <FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5">
   </FooterStyle>

   <HeaderStyle Font-Bold="True" ForeColor="White" 
       BackColor="#A55129">
   </HeaderStyle>
				
</asp:DataList>

The DataList control contains seven templates and seven styles:

The templates and styles supported by the DataList control
Figure 2. The templates and styles supported by the DataList control

The DataList control works quite similar the Repeater control (see my previous article on the Repeater control for a description of the various templates). However, it also supports the Edit, Update, and Cancel features found in the DataGrid control.

Let's modify the HTML code for our control, and I will explain each addition along the way.


<asp:DataList id="DataList1" 
     style="Z-INDEX: 101; 
	   LEFT: 16px; 
	   POSITION: absolute; 
	   TOP: 16px" 
	 runat="server"
     CellPadding="3" BackColor="#DEBA84" BorderWidth="1px"
     CellSpacing="2" BorderStyle="None" BorderColor="#DEBA84"
     GridLines="Both" 

Add the following attributes to the <asp:DataList> element:


     OnEditCommand="Edit_Command" 
     OnCancelCommand="Cancel_Command" 
     OnUpdateCommand="Update_Command"
     OnDeleteCommand="Delete_Command" 
     DataKeyField="title_id">

Later, we will add a few LinkButton controls to our DataList control to perform the functions of Edit, Update, Delete, and Cancel. The above attributes specify the methods to invoke when such LinkButton controls are clicked. I have also defined the key of this control to be the field title_id.

Next we add a <HeaderTemplate> element. The text within this element will be displayed as the title of the table.


   <HeaderTemplate>
      Titles
   </HeaderTemplate>

Displaying a title using the <HeaderTemplate> element
Figure 3. Displaying a title using the <HeaderTemplate> element

The <ItemTemplate> element allows you to display records from a database by binding them to the control. Here, I am displaying three fields (title_id, title, and price) from the Titles table (we will see this shortly).

			
   <ItemTemplate>
      <table border=1>
      <tr><td><b>ID : </b></td>
         <td>'<%# DataBinder.Eval(Container.DataItem, "title_id") %>'
         </td></tr>
      <tr><td><b>Title : </b></td>
         <td>'<%# DataBinder.Eval(Container.DataItem, "title") %>'
         </td></tr>
      <tr><td><b>Price : </b></td>
         <td>'<%# DataBinder.Eval(Container.DataItem, "price") %>'
      </td></tr>
      </table>

I have also added two LinkButton controls so that the user can edit or delete the record:


	<asp:LinkButton Text="Edit" CommandName="Edit" 
                      Runat="server" ID="edit" />
      <asp:LinkButton Text="Delete" CommandName="Delete" 
                      Runat="server" ID="delete" />
   </ItemTemplate>

Displaying a record
Figure 4. Displaying a record

Next, I add in the <EditItemTemplate> element so that textboxes can be displayed when the Edit button is clicked. I have also added two LinkButton controls to display the Update and Cancel buttons:


   <EditItemTemplate>
      <table border=1>
      <tr><td><b>ID : </b></td>
         <td>'<%# DataBinder.Eval(Container.DataItem, "title_id") %>'
         </td></tr>
      <tr><td><b>Title : </b></td>
         <td><asp:TextBox 
             Text='<%# DataBinder.Eval(Container.DataItem, "title") %>' 
             runat=server ID="title"/>
         </td></tr>
      <tr><td><b>Price : </b></td>
         <td><asp:TextBox 
             Text='<%# DataBinder.Eval(Container.DataItem, "price") %>' 
             runat=server ID="price"/></td></tr>
      </table>
      <asp:LinkButton Text="Cancel" CommandName="Cancel" 
                      Runat="server" ID="cancel" />
      <asp:LinkButton Text="Update" CommandName="Update" 
                      Runat="server" ID="update" />
   </EditItemTemplate>

Editing a record
Figure 5. Editing a record

That's it! We now turn our attention to writing the code to perform the data binding as well as the editing of the records.

First, import the relevant namespace for data access:

Imports System.Data.SqlClient

When the page is loaded for the first time, load the records from the database:


    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) _ 
						  Handles MyBase.Load
        'Put user code to initialize the page here
        If Not IsPostBack Then
            LoadData()
        End If

    End Sub

The LoadData() method binds the records from the Titles table (from the Pubs database) to the DataList control. Be sure to add a SqlDataAdapter control to your project.


    Public Sub LoadData()
        Dim ds As New DataSet
        SqlDataAdapter1.SelectCommand.CommandText = _
        "SELECT * FROM Titles"
        SqlDataAdapter1.Fill(ds, "titles_record")
        DataList1.DataSource = ds
        DataList1.DataBind()
    End Sub

When the Edit link is clicked, you need to set the index for the record to be edited:


    Sub Edit_Command(ByVal sender As Object, _
	                 ByVal e As DataListCommandEventArgs)
        ' to rebind the DataList to the data source to 
		' refresh the control.
        DataList1.EditItemIndex = e.Item.ItemIndex
        LoadData()
    End Sub

When the Cancel link is clicked, reset the edit index to -1:


    Sub Cancel_Command(ByVal sender As Object, _
        ByVal e As DataListCommandEventArgs)
        DataList1.EditItemIndex = -1
        LoadData()
    End Sub

When the Update link is clicked, you need to update the relevant record. Here I am extracting the key of the control (which is the title_id) and the values in the edit textbox:


    Sub Update_Command(ByVal sender As Object, _
                       ByVal e As DataListCommandEventArgs)
        Dim tbox As TextBox
        Dim title_id, title As String
        Dim price As Single

        '---retrieves the key for the row---
        title_id = DataList1.DataKeys(e.Item.ItemIndex)

        '---find the textbox control containing the title
        tbox = CType(e.Item.FindControl("title"), TextBox)
        title = tbox.Text
        '---find the textbox control containing the price
        tbox = CType(e.Item.FindControl("price"), TextBox)
        price = tbox.Text

        '---updates the database---
        Dim sql As String = "UPDATE titles SET title='" & _
                            title & "' , price=" & price & _
                            " WHERE title_id='" & title_id & "'"
        Dim conn As New SqlConnection("server=localhost; " & _
                        "user id =sa; password=;database=pubs")
        Dim comm As New SqlCommand(sql, conn)

        conn.Open()
        comm.ExecuteNonQuery()
        conn.Close()

        DataList1.EditItemIndex = -1
        LoadData()
    End Sub

Finally, you need to add the code for deleting a record. I will leave this as an exercise to the reader:


    Sub Delete_Command(ByVal sender As Object, _
                       ByVal e As DataListCommandEventArgs)
        '---retrieves the key for the row---
        Response.Write(DataList1.DataKeys(e.Item.ItemIndex))
        '---codes to delete row here----
        '
        '-------------------------------
    End Sub

Press F5 and run the application. You should see something like this:

Displaying and editing records using the DataList control
Figure 6. Displaying and editing records using the DataList control

Summary

Learning how to use the various data controls in ASP.NET can save you a lot of time in writing unnecessary code to perform mundane tasks. Hopefully this series has helped you to get started with ASP.NET data controls. Use the talkback feature below to let us know any tricks or tips you have!

Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.


Return to ONDotnet.com