ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[2] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[3] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[4] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[5] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[6] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[7] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[8] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[9] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[10] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
[11] ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
系列文章导航:
ASP.NET 2.0数据教程之四:使用ObjectDataSource展现数据
ASP.NET 2.0数据教程之六:编程设置ObjectDataSource的参数值
ASP.NET 2.0数据教程之七:使用DropDownList过滤的主/从报表
ASP.NET 2.0数据教程之八:使用两个DropDownList过滤的主/从报表
ASP.NET 2.0数据教程之十:使用 GridView 和DetailView实现的主/从报表
ASP.NET 2.0数据教程之十一:基于数据的自定义格式化
ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField
将这个新的模板列的页眉文本(HeaderText)设置成“Days on the Job”,并将其ItemStyle的水平对齐(HorizontalAlign)设置为居中(Center)。要调用DisplayDaysOnJob方法,我们需要给这个模板列添加一个ItemTemplate并加上如下的数据绑定代码:



Container.DataItem返回数据源对象中的一个相应的DataRowView对象给GridView。它的Row属性返回一个强类型化的Nothwind.EmployeesRow,然后再将其传递给DisplayDaysOnJob方法。这个数据绑定语法可以直接出现再ItemTemplate(就像下面的代码中那样)中或是赋值给Label控件的Text属性。
注意:除了传递一个EmployeesRow的实例,其实我们也可以仅仅传递HireDate的值,使用<%# DisplayDaysOnJob(Eval("HireDate")) %>就可以了。不过呢,Eval方法将返回一个object类型,所以我们就必须要修改DisplayDaysOnJob方法的签名以使其可以接受一个object类型的参数。我们不能将Eval("HireDate")调用的结果隐式的转换成一个DateTime类型,因为Employees表的HireDate字段是允许为空的。因此,我们需要使DisplayDaysOnJob方法可以接受一个object类型的参数,并判断这个参数是不是空值(我们可以使用Convert.IsDBNull(objectToCheck)来完成这个验证工作),然后再进行后面的操作。
就是因为这个,所以我还是选择了传递整个EmployeesRow实例。在下一节教程中,我们会看到一个更加合适使用Eval("columnName")来传递参数给格式化方法的例子。
在给我们的GridView添加了模板列并在ItemTemplate中添加了调用DisplayDaysOnJob方法的代码后,声明代码应该是这个样子:

DataKeyNames="EmployeeID"
2

3

4

5

6

</asp:TextBox>
7

8

9

10

11

12

13

14

15

16

</asp:TextBox>
17

18

19

20



21

22

23

24

25



Container.DataItem).Row) %>
26

27

28

29

30

31

完成了整节教程之后,页面在浏览器中的样子应该是图十六的这个样子。
图十六:“雇员在公司干了多久“也显示出来了
总结
在GridView控件中,相对于其他的列控件来说,模板列可以处理更加复杂的数据呈现。模板列主要用于这样一些情况:
· 一个GridView列中需要显示多个数据列
· 使用一个Web控件来展示数据比一段简单的文本更好
· 页面的输出取决于绑定到GridView的数据,比如说元数据或者说是数据的重新格式化
除了自定义数据的显示,模板列也用于编辑和插入数据时的用户界面的自定义,这个我们在后面的章节中将会讲到。
接下来的两节中,我们会继续讨论模板,我们会先看看在DetailsView中使用模板列的情况。跟着我们再去看看FormView,这玩意儿就是用模板来实现一个更加复杂的呈现,当然,用的是一大堆的字段。
编程愉快!