How to use .Net ListItem in the real world
When starting out with .Net the built-in server controls can appear a bit daunting - especially if coming from a classic ASP or PHP background (where you simply write HTML elements out as a string). In this post i will run through an every day example of how to use a ListItem to display data and customise the output via the ItemTemplate.
A .Net ListItem can be used to bind data from a datasource (SQLDataReader, DataTable, ArrayList, GenericList etc...) to display to the end user. The display can be customised through the use of the <itemTemplate> as follows:
Source Code Example (asp.Net):
<asp:DataList ID="dlCountries" runat="server">
<HeaderTemplate>
<table class="fs1" cellpadding="5" cellspacing="1" style="border:1px solid #CCC; background-color: #f7f7f7; margin:20px;">
<tr class="bold"><td>Country ID</td><td>Country Name</td></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Container.DataItem("countryID")%></td>
<td><%#Container.DataItem("countryName")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
NOTE: When programing functionality into your ListItem or Repeater you may come accross the following error:
e.Item.FindControl throws Object reference not set to an instance of an object
the solution is to make sure you're in the correct ListItemType (usually ListItemType.Item or ListItemType.AlternatingItem)
Source Code Example (vb.net):
Protected Sub dlCountries_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlCountries.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
... code
End If
End Sub