13. November 2007 20:24
Recently I had to bind to an array of strings and I wasn't sure how to show the value of the current item. After a little bit of help from the DevTheo and a little bit of thinking I figured out the solution was very simple. All i had to do was bind it like this:
<%# Container.DataItem %>
So what is this expression exactly? The <%# %> means this is a DataBinding expression and Container.DataItem is an alias for the current item in the datasource. In other words, if you are binding to a collection of objects Container.DataItem is the current row of that collection.
If we use a DataView (default type when using SQLDatasource) to bind then Container.DataItem is a DataRowView. For a collection of objects of type Animals the type will be Animal and for an array of strings Container.DataItem will be a string.
Since .NET doesn't know to what type of collection object you will bind to DataItem will return an object. For C# you will have to cast your DataItem:
<%# ((DataRowView)Container.DataItem)["SomeProperty"] %>
There's another way of achieving the same result and that is using DataBinder.Eval.
<%# DataBinder.Eval(Container.DataItem, "SomeProperty")%>
DataBinder.Eval is a helper method that uses reflection to find the type of the DataItem in order to display the data correctly. The benefit of the Eval method is that if your type changes in the future you don't need to change the code, but in the other hand reflection causes performance to slow down.