ASP.NET server controls provide a rich environment to produce high quality web sites. Sometimes though, you just want to go that little bit further.
DataLists offer a convenient way to render lists with data that can be fully customized using templates. I was last experimenting with a
DataList control and I soon found two features that where not immediately available out of the box:
- Providing visual feedback on which row the mouse is over.
- Enabling the user to select a
DataListItem by clicking anywhere on the item.
I will show how this can be easily accomplished.
Using the code
The example provided assumes the following things:
- The Northwind database is available (the example uses the local SqlExpress connection with the default parameters).
DataList will be bound to the Northwind database and shows some info from the Employee table.
DataList uses '
RepeatLayout (otherwise the proposed highlighting solution does not work).
After you have implemented the binding for the
DataList, you need to modify the
ItemTemplate by adding a
LinkButton as the first control, let's call it for a change '
SelectButton'. The documentation reads the
ItemCommand event will be raised when any button of the
ItemTemplate is clicked. Since we don't want to use this
LinkButton directly for selecting a row, we are going to hide it. This can be done by adding a
By setting the
display style attribute to
none, we assure that the button will be rendered and is available in the DOM structure.
Once we have a button available, we know that when it's clicked, it will trigger the
ItemCommand event. This can be achieved as follows:
protected void DataList1_ItemDataBound(object sender,
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
"this.oldClass = this.className;" +
" this.className = 'EntryLineHover'");
"this.className = this.oldClass;");
The code is executed during the
ItemDataBound event. Here, we add new attributes to the rendered
DataListItems. The first two attributes have to do with the highlighting of the row when the mouse hovers over it. We just switch between two CSS styles.
The third attribute serves to simulate a click on the hidden '
GetPostBackEventReference refers to the first control in the item, the '
SelectButton', and will result, for example, in the following script added to the
OnClick event of the rendered
In order to show info about the selected
DataListItem, you could use:
protected void DataList1_ItemCommand(object source,
LastNameLabel is the name of the label in the
ItemTemplate that holds the last name of the selected employee.
The basic idea of implementing highlight and selection comes from an article that deals with the same issues but then for
DataGrids instead of
The article can be found here: Steps to Write GridView PostBack Events.