DataList Control

You've traveled the long and arduous journey of reading through my 3 other articles on using the DataGrid and Repeater controls in ASP.Net. This is the last but not least, the DataList. You can look at it as either a stripped-down DataGrid or a beefed-up repeater, but either way it's got a good mix of flexibility and functionality that will make it the best choice in many situations.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 21
July 20, 2004
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement


Previous articles on this topic include DataGrid and Repeater controls.


Introduction

In my last article, I detailed how to make good use of the Repeater control. By setting up a template for the repeating data, you saw how easy it was to surface data from a dataset onto a web page. Beyond just merely repeating or displaying the data, I illustrated a real-life application of its use, putting it to work in an e-commerce environment. To do this I explain what is meant by 'event bubbling' and how to use it effectively.

You'll find it an easy transition to now move into the DataList control. Its use is very similar to the repeater, but it has some additional flexibility and functionality. You have more control over the display of the data, as well as provisions for data selection and editing.

Let's get right into the code, and I'll explain how it works along the way

Into the Code

Like any data-bound control in .Net, we'll start off the example by retreiving the actual data with which to populate the DataList. We don't really need to re-invent the wheel here; we can use very similar code to what is used with a repeater. We'll call the binding subroutine doBinding():

Sub doBinding()

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _

"Ole DB Services=-4; " & _

"Data Source=C:\Inetpub\wwwroot\test.mdb"

Dim dbConnection As OleDbConnection = New OleDbConnection(strConn)

Dim strSQL As String = "SELECT * FROM products"

Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter( strSQL, strConn)

Dim dataSet As DataSet = New DataSet

dataAdapter.Fill(dataSet)

dList.DataSource = dataSet

dList.DataBind()

End Sub

Nothing too groundbreaking here. We just made the connection, established the query string with results in a dataset filled with the products data. Then we instantiate the datalist and bind the data to it.

Now of course this will all do exactly nothing unless we call the subroutine at some event. And naturally we will use the page load event to call it:

sub page_load( source as Object, e as EventArgs )

if not isPostBack then

doBinding()

end if

end sub

Bring on the DataList

Now we get to the meat -- the actual implementation of the DataList. I will first show it in its most basic form, just using the required ItemTemplate and embedding some simple HTML.

<form runat="server">

<asp:DataList id="dList" runat="server" RepeatColumns="3"

RepeatDirection="Horizontal">

<ItemTemplate>

Desc: <%# Container.DataItem("description") %>

<br />

Mfg: <%# Container.DataItem("manufacturer") %>

<br />

Color: <%# Container.DataItem("color") %>

<br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %> Picture:

<br />

<img src='<%# Container.DataItem("imgPath") %>' />

</ItemTemplate>

</asp:DataList>

</form>

Now you'll notice the two things different from a repeater, the RepeatColumns and RepeatDirection properties. What this does in effect is throw the data into an HTML table (unless you modify the RepeatLayout), configured to the number of columns/rows in the direction that you specify. We could have easily added in some quick formatting with the following optional properties:

<asp:DataList id="dList" runat="server" RepeatColumns="3"

RepeatDirection="Horizontal" GridLines="Vertical" BorderWidth="1px" RepeatColumns="3" RepeatDirection="Horizontal" BorderStyle="Solid" BorderColor="#E0E0E0" BackColor="#FFC0C0" ForeColor="#80FF80" >

So at this point you're thinking that the only thing that the DataList really does is save you having to manually include the code to output a repeater into a table. So far you're right, but I haven't gotten into the selecting or editing capabilities. Let's do that now.

Selecting/Editing Templates in a DataList

Suppose we wanted to strip down the initial display and only provide a picture and description of the product. This is very practical in a shopping cart, as this would preserve landscape, and allow users to click on individual products to get more specific information. We can do that through the SelectedItemTemplate and by modifying the SelectedIndex of the DataList.

So let's modify the item template to only provide the description and a picture:

<ItemTemplate>

<asp:LinkButton runat="server" commandName="select">

<%# Container.DataItem("description") %>

</asp:LinkButton>

<br /><img src='<%# Container.DataItem("imgPath") %>' />

</ItemTemplate>

Then we will bubble the click on the LinkButton up to the container with OnItemCommand:

<asp:DataList id="dList" runat="server"

onItemCommand="getItem"
OnEditCommand="editItem"

RepeatDirection="Horizontal" RepeatColumns="3">

And this necessitates a subroutine called getItem. This subroutine will determine the index of the item clicked, and set the SelectedIndex to that one:

Sub getItem( s as object, e as DataListCommandEventArgs )

dList.SelectedIndex = e.Item.ItemIndex

doBinding()

End Sub

And now all we need to do is modify the selectedItemTemplate, to provide the additional information:

<SelectedItemStyle BackColor="#CCCCCC">

</SelectedItemStyle>

<SelectedItemTemplate>

Desc: <%# Container.DataItem("description") %>

<br />

Mfg: <%# Container.DataItem("manufacturer") %>

<br />

Color: <%# Container.DataItem("color") %>

<br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %>

<br />

<img src='<%# Container.DataItem("imgPath") %>' /><br />

<asp:LinkButton runat="server" commandName="buy" text="buy" />

<% if isAdmin() then %>

<asp:LinkButton runat="server" commandName="edit" text="edit" />

<% end if %>

</SelectedItemTemplate>

Now when you click the LinkButton for one item, it will display its extended info, as well as have a gray background. Users have a link that says 'buy', which you could configure to send them off to a page to do credit card processing and shipping and whatnot.

Now suppose you're the site administrator. You should be able to edit the items. You might have opted to use the DataGrid for this. However, you like the idea of having full control of your editing abilities, and that's what the DataList provides. (For example, you can very easily toss validation controls into your editing template). I have included the fake checking routine called isAdmin(); you can use whatever device you want. All that matters is that somehow the administrator gets the extra little link that says 'edit'.

If you go back to the actual DataList configuration, you'll notice I placed in there the 'onEditCommand' method handler. It wants to hand things off to a routine called editItem, which will look like this:

Sub editItem( s as object, e as DataListCommandEventArgs )

dList.EditItemIndex = e.Item.ItemIndex

doBinding()

End Sub

And now that we've set the EditItemIndex, we actually have to do something with it by setting the EditItemTemplate. We'll place every attribute in a text box for editing, and provide the buttons to update, delete, and cancel.

<EditItemTemplate>

Desc:

<asp:TextBox runat="server" id="desc" text='<%# Container.DataItem("description") %>' />

<br />

Mfg: <asp:TextBox runat="server" id="mfg" text='<%# Container.DataItem("manufacturer") %>' />

<br />

Color: <asp:TextBox runat="server" id="clr" text='<%# Container.DataItem("color") %>' />

<br />

Cost: <asp:TextBox runat="server" id="cst" text='<%# Container.DataItem("price") %>' />

<br />

Img: <asp:TextBox runat="server" id="img" text='<%# Container.DataItem("imgPath") %>' /><br />

<asp:LinkButton runat="server" commandName="Update" text="upd" /> |

<asp:LinkButton runat="server" commandName="Delete" text="del" /> |

<asp:LinkButton runat="server" commandName="Cancel" text="cancel" />

</EditItemTemplate>

You can see just how easy it was to make an item editable. And of course you could very simply throw into validation controls to make sure the cost field is still numeric and so forth. But you may be a little disappointed when you click on 'upd' and nothing happens. That's because we haven't installed the method handlers. To provide the actual update, delete and cancel methods, you need to implement the onUpdateCommand, onDeleteCommand, and onCancelCommand handlers of the DataList.

I'll show you how to implement the onCancelCommand, but the other two you can refer to my article on editing in a DataGrid (http://www.aspfree.com/c/a/.NET/Return-of-the-DataGrid-Paging-and-Editing-Explained/2/), as there's no need to duplicate all the code!

The dataList will now look like this:

<asp:DataList id="dList" runat="server"

OnItemCommand="getItem"

OnEditCommand="editItem"

OnUpdateCommand="UpdateItem"

OnDeleteCommand="DeleteItem"

OnCancelCommand="doCancel"

RepeatDirection="Horizontal" RepeatColumns="3">

And the doCancel() subroutine looks like this:


Sub doCancel( s as object, e as DataListCommandEventArgs )

dList.SelectedIndex = -1

dList.EditItemIndex = -1

doBinding()

End Sub

So where are we now? I've showed you how to install a DataList, pump it full of data, and configure its output. You can select a specific item to see its extended properties, and then if you're the administrator you have editing capabilities. When you click cancel, it takes you back to the original, non-selected dataList. If you want the ability to actually update or delete data, (which you will) you can use the code from my other article: http://www.aspfree.com/c/a/.NET/Return-of-the-DataGrid-Paging-and-Editing-Explained/2/

Conclusion

I've given you enough code and explanation of how the DataList works to at least make you dangerous. If you need any deeper information, I would advise you visit the class information at the MSDN library: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIWebControlsDataListClassTopic.asp

Thanks for reading! To save you a lot of choppy copying and pasting, here's all the code in one big chunk:

<%@ Page Language="VB" Debug="true" %>

<%@ import Namespace="System.Data" %>

<%@ import Namespace="System.Data.OleDb" %>

<script runat="server">


sub page_load( source as Object, e as EventArgs )

if not isPostBack then

doBinding()

end if

end sub


Sub doBinding()

Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _

"Ole DB Services=-4; " & _

"Data Source=C:\Inetpub\wwwroot\test.mdb"


Dim dbConnection As OleDbConnection = New OleDbConnection(strConn)


Dim strSQL As String = "SELECT * FROM products"


Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter( strSQL, strConn)

Dim dataSet As DataSet = new DataSet

dataAdapter.Fill(dataSet)


dList.DataSource = dataSet

dList.DataBind()

End Sub


Sub getItem( s as object, e as DataListCommandEventArgs )

dList.SelectedIndex = e.Item.ItemIndex

doBinding()

End Sub


Sub editItem( s as object, e as DataListCommandEventArgs )

dList.EditItemIndex = e.Item.ItemIndex

doBinding()

End Sub


Sub UpdateItem( s as object, e as DataListCommandEventArgs )

End Sub


Sub DeleteItem( s as object, e as DataListCommandEventArgs )

End Sub


Sub doCancel( s as object, e as DataListCommandEventArgs )

dList.SelectedIndex = -1

dList.EditItemIndex = -1

doBinding()

End Sub


</script>

<html>

<head>

</head>

<body>

<form runat="server">

<asp:DataList id="dList" runat="server"

onItemCommand="getItem"

OnEditCommand="editItem"

OnUpdateCommand="UpdateItem"

OnDeleteCommand="DeleteItem"

OnCancelCommand="doCancel"

RepeatDirection="Horizontal" RepeatColumns="3">

<ItemTemplate>

<asp:LinkButton runat="server" commandName="select"><%# Container.DataItem("description") %></asp:LinkButton>

<br />

<img src='<%# Container.DataItem("imgPath") %>' />

</ItemTemplate>

<SelectedItemStyle BackColor="#CCCCCC">

</SelectedItemStyle>

<SelectedItemTemplate>

Desc: <%# Container.DataItem("description") %>

<br />

Mfg: <%# Container.DataItem("manufacturer") %>

<br />

Color: <%# Container.DataItem("color") %>

<br />

Cost: <%# FormatCurrency( Container.DataItem("price")) %>

<br />

<img src='<%# Container.DataItem("imgPath") %>' /><br />

<asp:LinkButton runat="server" commandName="edit" text="edit" />

</SelectedItemTemplate>

<EditItemTemplate>

Desc:

<asp:TextBox runat="server" id="desc" text='<%# Container.DataItem("description") %>' />

<br />

Mfg: <asp:TextBox runat="server" id="mfg" text='<%# Container.DataItem("manufacturer") %>' />

<br />

Color: <asp:TextBox runat="server" id="clr" text='<%# Container.DataItem("color") %>' />

<br />

Cost: <asp:TextBox runat="server" id="cst" text='<%# Container.DataItem("price") %>' />

<br />

Img: <asp:TextBox runat="server" id="img" text='<%# Container.DataItem("imgPath") %>' /><br />

<asp:LinkButton runat="server" commandName="Update" text="upd" /> |

<asp:LinkButton runat="server" commandName="Delete" text="del" /> |

<asp:LinkButton runat="server" commandName="Cancel" text="cancel" />

</EditItemTemplate>

</asp:DataList>

</form>

</body>

</html>

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials