What is Container.DataItem exactly?

2020-05-24 20:40发布

问题:

What is Container.DataItem exactly?

回答1:

This article might help you understand. Quote:

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.

This blog entry gives help on when to use. Quote:

Container.DataItem is a runtime alias for the DataItem for this specific item in the bound list. For a grid which displays 10 rows of data, this is one row from the datasource. The actual type of DataItem is determined by the type of the datasource. For example, if the datasource is a Dataview, the type of DataItem is DataRowView. If the type of the datasource is an array of strings, the type of DataItem is String. If the datasource is a collection of strongly-typed objects (for example "Employees" objects), the type of DataItem is Employees.

Each of these cases requires a slightly different databinding expression, with further differences between VB and C#.



回答2:

I ran across this same question specifically in the context of trying to access Container.DataItem from within the code-behind. Container exists in the aspx/ascx code but does not exist within the code-behind. By looking at the generated C# code, I saw that it's a casted reference to BindingContainer on the specific control being bound.

Equivalent code-behind code for Container.DataItem is this:

var ddl = (DropDownList) source;
var dataItem = ((RepeaterItem) ddl.BindingContainer).DataItem;


标签: asp.net