Cowboy Galaxy

Learner

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
DataBinder.Eval的基本格式
View Code
 1 //第一种
 2 <%# DataBinder.Eval(Container.DataItem,"xxxx")%>
 3 //第二种
 4 <%# DataBinder.Eval(Container,"DataItem.xxxx")%>
 5 //第三种(比前两种效率高)需要<%@ Import namespace="System.Data" %>
 6 <%# ((DataRowView)Container.DataItem)["xxxx"]%>
 7 //这种用法其实和下面的是一个道理。
 8 <%# ((DictionaryEntry)Container.DataItem).Key%>
 9 
10 Text='<%# DataBinder.Eval(Container.DataItem, "字段") %>'
11 //这样的方法是最快的
12 
13 Text='<%# GetPrice() %>'
14 //也可以绑定方法,但方法要是public的
15 
16 Text='<%# "CarDetails.aspx?CarID=" + DataBinder.Eval(Container.DataItem, "CarID") %>'
17 //还可以连接多个字段
18 //关键是Container这个东西,它比较神秘。它的名称空间是System.ComponentModel。对于它我还需要进一步理解。


DataBinder.Eval实现判断选择

View Code
 1 <asp:TemplateColumn HeaderText="性别">
 2 
 3 <ItemTemplate>
 4 
 5 <%# DGFormatSex(Convert.ToString(DataBinder.Eval(Container.DataItem,"xb"))) %>
 6 
 7 </ItemTemplate>
 8 
 9 </asp:TemplateColumn>
10 
11 //cs里定义DGFormatSex方法
12 
13 protected string DGFormatSex(string xb)
14 
15 {
16 
17  if(xb == "1")
18 
19  return "";
20 
21  else
22 
23  return "";
24 
25 }


DataBinder.Eval用法范例

View Code
 1 //显示二位小数
 2 
 3 <%# DataBinder.Eval(Container.DataItem, "UnitPrice""${0:F2}"%>
 4 
 5 {0:G}代表显示True或False
 6 
 7 <ItemTemplate>
 8 
 9  <asp:Image Width="12" Height="12" Border="0" runat="server"
10 
11  AlternateText='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "{0:G}") %>'
12 
13  ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Discontinued""~/images/{0:G}.gif"%>' />
14 
15  </ItemTemplate>
16 
17 转换类型
18 
19 ((string)DataBinder.Eval(Container, "DataItem.P_SHIP_TIME_SBM8")).Substring(4,4)
20 
21 {0:d} 日期只显示年月日
22 
23 {0:yyyy-mm-dd} 按格式显示年月日
24 
25 {0:c} 货币样式
26 
27 灵活的运用数据绑定操作
28 
29 绑定到简单属性:<%#UserName%>
30 
31 绑定到集合:<asp:ListBox id="ListBox1" datasource='<%# myArray%>' runat="server">
32 
33 绑定到表达式:<%#(class1.property1.ToString() + "," + class1.property2.ToString())%>
34 
35 绑定到方法返回值:<%# GetSafestring(str) %>
36 
37 绑定到Hashtable:<%# ((DictionaryEntry)Container.DataItem).Key%>
38 
39 绑定到ArrayList:<%#Container.DataItem %>
40 
41  
42 
43 若数组里里放的是对象则可能要进行必要的转换后再绑定如:
44 
45 <%#((对象类型)Container.DataItem).属性%>
46 
47  
48 
49 绑定到DataView,DataTable,DataSet:
50 
51 <%#((DataRowView)Container.DataItem)["字段名"]%>
52 
53 <%#((DataRowView)Container.DataItem).Rows[0]["字段名"]%>
54 
55 要格式化则:
56 
57 <%#string.Format("格式",((DataRowView)Container.DataItem)["字段名"])%>
58 
59 <%#DataBinder.Eval(Container.DataItem,"字段名","格式")%>


 


当然为了方便一般使用最多的就是DataBinder类的Eval方法了.不过这样对于同时要绑定大量的数据效率要低一些

绑定到DataSet、DataTable时:

<%#((System.Data.DataRowView)Container.DataItem)["字段名"]%>

<%#((System.Data.DataRowView)Container.DataItem)[索引]%>

绑定到DataReader时:

<%#((System.Data.Common.DbDataRecord)Container.DataItem)[索引]%>

<%#((System.Data.Common.DbDataRecord)Container.DataItem)["字段名"]%>

绑定到DataReader:

<%#((IDataReader)Container.DataItem).字段名%>
posted on 2011-05-10 14:09  WarLock!  阅读(410)  评论(1编辑  收藏  举报