Daily Archives: 5 June 2009

Index of an Item of a ListView

When you are working with a GridView, it is usually pretty easy to ascertain the index for a particular row inside an event handler for that row e.g. in an event handler for the RowCreated event, the row-index for the row which was just created is e.Row.RowIndex. The GridViewRowEventArgs serves it right up!

With a ListView, you need to burn a few more calories to get that number. The ListViewItemEventArgs does not contain the index. So, in an event handler for the ItemCreated event, you can get the index for that item with the following statement:

int index = ((System.Web.UI.WebControls.ListViewDataItem)e.Item).DataItemIndex;

You cast the item (which is a ListViewItem) to the ListViewDataItem type. That type has a Property called DataItemIndex.

Not really so hard after all.