Monday, December 17, 2007
« Code Camp 2008.1 Update | Main | Code Camp 2008.1 Update »

The new ListView control in ASP.Net is pretty cool.  It is really flexible and often makes life pretty easy for me.  But there is one thing that doesn't make sense to me.

It isn't simple to figure out which item is the "Edit Item" during databinding.  It isn't impossible, but it seems more complicated then I'd expect.  During ItemDataBound() you can test the item's type:

        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            //do something
        }

Remember that with a ListView, there are no rows, so we refer to Items. 

Unfortunately, the options for ListViewItemType only include DataItem, InsertItem, and EmptyItem.  All of those are helpful, but what about EditItem? So the next logical thing to do is use the ListView's EditIndex.  All I'd have to do is compare the current index to the EditIndex and I'll know if I'm on the edit item.  ListViewItemEventArgs has an Item property but there doesn't seem to be an Index or CurrentIndex property.  So the comparison won't be so easy.  We'll here it is, the way to figure it out:

    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;

            if (dataItem.DisplayIndex == ListView1.EditIndex)
            {
                //do something
            }
        }
    }

I hope this information is helpful.

Friday, January 04, 2008 10:49:09 AM (Eastern Standard Time, UTC-05:00)
Thanks man, this was exactly what I was looking for! It's funny that we work at the same company and this came up when I searched for this.

You're the man Schwammy!
Thursday, July 10, 2008 1:02:19 PM (Eastern Standard Time, UTC-05:00)
I know it's been about 7 months, but if you are still testing for the edit item this way, I recommend a change.

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e) {
if (e.Item == ListView1.EditItem) {
// do something.
}
}
Ventaur
Friday, February 13, 2009 11:40:55 AM (Eastern Standard Time, UTC-05:00)
And, after 7 more months... I can't get Ventaur's example to work. Schwammy's does so I 'm going to use his.
Rob
Wednesday, February 18, 2009 10:14:25 AM (Eastern Standard Time, UTC-05:00)
Rob,
I am glad it is working for you!
-Schwammy
Saturday, July 04, 2009 5:18:25 AM (Eastern Standard Time, UTC-05:00)
Schwammy,

I am using the datalist control and I was struggling since two days to find controls in the edit mode and your code works perfectly fine. I am very glad. Thanks a lot my friend.

Cheers
Narendra
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):