View Single Post
  #6 (permalink)  
Old June 15th, 2009, 12:10 PM
philip_cole philip_cole is offline
Friend of Wrox
Points: 894, Level: 11
Points: 894, Level: 11 Points: 894, Level: 11 Points: 894, Level: 11
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Sep 2005
Location: London, , United Kingdom.
Posts: 166
Thanks: 2
Thanked 33 Times in 33 Posts
Default

Sorry Lee, there is a slight error in your code.

OK I had to dig deep to find it, but it's worth mentioning that ItemCreated is raised each time the layout of the ListView is created, not just when databinding happens. For example if you do a postback later on, ItemCreated will be raised but DataItem won't have a value, so when you try to set view["ProductText"] it will raise a NullReferenceException.

So you just need to add a null check to your ItemCreated event:
Code:
protected void listProducts_ItemCreated(object sender, ListViewItemEventArgs e)
{
   if (e.Item.ItemType == ListViewItemType.DataItem)
   {
      ListViewDataItem dataItem = (ListViewDataItem) e.Item;

      if(dataItem.DataItem != null)
      {
         string prodtype = (string) DataBinder.Eval(dataItem.DataItem, "ProductType");
 
         DataRowView view = (DataRowView)dataItem.DataItem;
 
         if (prodtype == "Sample")
         {
            view["ProductText"] = "Sample product";
         }
      }
   }
}
Phil