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.

7 thoughts on “ASP.Net ListView EditItem?

  1. I’ve been trying to crack this for about four hours today. I’m thankful to you not only posting the solution, but for leaving it up for a DECADE! Thank you! 2/17/2017

    Reply
  2. Just to prove how a little nugget of code can be useful years down the track – you helped me out 4 years after your original post… and I second the fact that Ventaur’s approach doesn’t work (I had seen that approach posted elsewhere, tried it and it didn’t work, so kept searching, found this approach and BOOM, it works… thanks!).

    Reply
  3. 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

    Reply
  4. 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.
    }
    }

    Reply

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>