"<%# DataBinder.Eval(Container.DataItem,"ColumnName") %>"在Item Template中的作用是什么?"

15

我第一次使用 DataList。一切正常,我能够在屏幕上看到数据。 我在项模板中使用了这段代码。

<asp:DataList ID="DataList1" runat="server">
    <FooterTemplate>          
    </FooterTemplate>
    <HeaderTemplate>              
    </HeaderTemplate>
    <ItemTemplate>          
        <%# DataBinder.Eval(Container.DataItem,"AA") %>
        <%# DataBinder.Eval(Container.DataItem,"BB") %>
        <%# DataBinder.Eval(Container.DataItem,"CC") %>
    </ItemTemplate>
</asp:DataList>

我正在绑定的是 DataTable

DataTable dt = new DataTable();
dt.Columns.Add("AA");
dt.Columns.Add("BB");
dt.Columns.Add("CC");

dt.Rows.Add("1", "2", "3");
dt.Rows.Add("10", "20", "30");
dt.Rows.Add("100", "200", "300");
dt.Rows.Add("1000", "2000", "3000");

DataList1.DataSource = dt;
DataList1.DataBind();
< p > DataBinder.Eval(Container.DataItem,"ColumnName") 究竟是做什么的? 提前感谢您。


以下是对下面答案的补充说明。由于DataBinder.Eval(Container.DataItem,"memberName")后期绑定,因此性能会受到影响。请参阅本文以获取早期绑定语法,从而获得更高效和易于调试的代码:http://www.devcurry.com/2011/02/how-to-avoid-databindereval-in-aspnet.html - ingredient_15939
2个回答

17

第一个参数: Container.DataItem 指的是绑定到当前容器的数据源datasource

第二个参数: 应该被评估的DataItem上的公共属性。

因此,Eval使用反射来评估DataItem上的公共属性。

例如:

在您的情况下,它评估DataTable上的BB列。


8
以下代码行将根据表中的行数执行多次。
<%# DataBinder.Eval(Container.DataItem,"AA") %>
<%# DataBinder.Eval(Container.DataItem,"BB") %>
<%# DataBinder.Eval(Container.DataItem,"CC") %>

每次循环,Container.DataItem 将具有数据表中行的相应 DataRowView
该项中发生的情况类似于以下代码。
DataView dataView = new DataView(dt);
foreach (DataRowView dataRow in dataView)
{              
    System.Diagnostics.Debug.WriteLine(DataBinder.Eval(dataRow,"AA").ToString());
    System.Diagnostics.Debug.WriteLine(DataBinder.Eval(dataRow,"BB").ToString());
    System.Diagnostics.Debug.WriteLine(DataBinder.Eval(dataRow,"CC").ToString());
}

得到的输出将是

1 2 3 10 20 30 100 200 300 1000 2000 3000


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接