Repeater中的数据绑定。C#

在aspx.cs中

myRepeater.DataSource = dataTabale; myRepeater.DataBind();

页面aspx中

可以用

((DataRowView)Container.DataItem)["字段"].ToString() //再C#中需要转成DataRowView,而VB.NET中不需要转 //或者 <%# DataBinder.Eval(Container.DataItem,"state") %> <%# Eval("State") %> //是前者的简写

这两种绑定方式都可以。但是有点区别。

网站http://weblogs.asp.net/rajbk/archive/2004/07/20/what-s-the-deal-with-databinder-eval-and-container-dataitem.aspx中的解释比较详细。

Array of Strings: VB/C# <%# Container.DataItem %> Field from DataView: VB <%# Container.DataItem("EmployeeName") %> C# <%# ((DataRowView)Container.DataItem)["EmployeeName"] %> Property from a collection of objects: VB <%# Container.DataItem.CustomerName %> C# <%# ((Customer)Container.DataItem).CustomerName %> Non-String property from a collection of objects: VB <%# CStr(Container.DataItem.CustomerID) %> C# <%# ((Customer)Container.DataItem).CustomerID.ToString() %>

来外的解释:

DataBinder.Eval uses reflection to get a value of a property of the
dataitem object. This is less performant than casting the dataitem
object to its actual type, and then access its property. The only
reason to use DataBinder.Eval is that the syntax may be/look simpler.

I always cast it to its actual type, which means it looks like this:
<%# ((MyObject)Container.DataItem).MyProperty %>
Or in case you are binding against a datatable, the dataitem is of the
the type datarowview:
<%# ((DataRowView)Container.DataItem)["MyField"] %>

 

The DataItem property returns a reference to an object, and
System.Object doesn't have an indexer defined. You'd have to cast the
DataItem return value to the proper type before the first expression
would compile.

DataBinder.Eval works because it will use reflection to dig out the
property with the name of "Author" dynamically. The second expression
would be the one to use in this case because it is the only one to
work.

你可能感兴趣的:(asp.net)