Monday, May 4, 2009

Accessing Data Bound to ListView

If we try to access data that are bound to listview by the following code:
ListViewDataItem lvDataItem = ListView.Item[index];

We'll find that lvDataItem is null.

In fact, all the ListViewDataItem in listview's Item collection are null. The only time it is not null is in ItemDataBound event of ListView. I guess it is designed this way to save memory space. So what if we need to access the data outside ItemDataBound event?

The answer is simple. Just specify DataKeyNames property of ListView like this:
DataKeyNames="ProductName, UnitPrice"

Then, we can access any data:

1 comment:

Tom said...

That's brilliant cheers!