Programing and Manipulating the .Net ListItem

Posted by Elliott Nash | Filed under , , , ,

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

 

Comments

November 14, 2009 16:44

Paula Dorf Makeup Brushes

Paula Dorf Makeup Brushes

Paula Dorf Makeup Brushes United Kingdom

February 20, 2010 12:50

joie clothing

Great article I will link to it from my joie clothing website.  Thank you.

joie clothing

March 6, 2010 00:00

Louis Bourn

Solid blog. I got a lot of good info. I've been following this technology for awhile. It's intriguing how it keeps shifting, yet some of the core elements stay the same. Have you seen much change since Google made their latest acquisition in the field?

Louis Bourn United States

March 10, 2010 12:42

Aimee Sabastian

It does seem that everybody is into this kind of stuff lately. Don’t really understand it though, but thanks for trying to explain it. Appreciate you shedding light into this matter. Keep it up

Aimee Sabastian United States

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading