一、容器与控件的父子关系
当我们使用DataList、Reapter、GridVieW控件的模板时,经常会在模板中使用Web服务器控件,
那么,浏览该页面时,系统会构建控件树。这时,容器的每行(或项)与控件便形成父子关系。
我们把包含Web控件的容器项(DataListItem)或行(GridViewRow),叫作父容器,把被包含在
行(项)下面的Web服务器控件叫作子控件。
如:下例,在UI部分,DataLIst的 <itemtemplate> </itemtemplate>中嵌入了Web服务器控件Label,
那么,当运行时,DataList的每项(DataListItem)与该项下的Label控件,便形成了父子容器与控件。
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<itemtemplate>
<table class="auto-style1">
<tr>
<td class="auto-style2">序号:</td>
<td class="auto-style2"><%# DataBinder.Eval(Container.DataItem,"id")%></td>
</tr>
<tr>
<td>姓名:</td>
<td><%# DataBinder.Eval(Container.DataItem,"name") %></td>
</tr>
<tr>
<td>地址</td>
<td><%#DataBinder.Eval(Container.dataitem,"nPlace") %></td>
</tr>
<tr>
<td>现金:</td>
<td>
<asp:Label ID="Cash" runat="server"></asp:Label></td>
</tr>
</table>
</itemtemplate>
</asp:DataList>
特别说明:(1)、当控件位于DataList容器中,其父容器为该控件所在的Datalist容器的项,即:DataListItem.
(2)、当控件位于Repeater容器中,其父容器为该控件所在的Repeatert容器的项,即:ReapterItem.
(3)、当控件位于GrivView容器中,其父容器为该控件所在GridView容器的行,即:GridViewRow.
二、应用场景
在使用DataList、Reapter、GridVieW控件的模板情况下,当需要在每项(或行)中显示数据时,可以关键字Container
引用控件的容器(或容器的属性,如:Container.DataItem)。另外,在编程模式下,当我们需要改变GridVieW表格中的
某行某列的数据时,需要以NamingContainer属性来引用控件所在的容器行,即:GridViewRow。注:Container只能用在
声明性<%# %>表达式中,而在编程模式下,则需要用NamingContainer来指定控件的父容器。
三、技术实现
1、以数据绑定表达式形式引用数据容器。即:DataBinder.Eval(Container.DataItem,"字段名"),其中字段名为:
与容器控件绑定的数据库表中的一个字段。
具体如下例:
<asp:DataList ID="DataList1" runat="server">
<itemtemplate>
<table class="auto-style1">
<tr>
<td>现金:</td>
<td>
<asp:Label ID="Cash" runat="server">DataBinder.Eval(Container.DataItem,"money")</asp:Label></td>
</tr>
</table>
</itemtemplate>
</asp:DataList>
2、以编程方式引用数据容器。即:通过控件的NamingContainer属性来获取对其父容器的引用。
如,下例:需要显示GridView第2行第2例的文本内容,那么先通过该行中所包含的LinkButton1的NamingContainer属性
来定位GridView行,再把该行赋值给MyParent,然后,引用MyParent.Cells[1].Text属性来显示单元格的文本内容。
具体代码段如下:
protected void Grid_Row_Com(object sender, GridViewCommandEventArgs e)
{
LinkButton MyLink=(LinkButton) GridView1.Rows[1].FindControl("LinkButton1");
GridViewRow MyParent =(GridViewRow) MyLink.NamingContainer;
Response.Write(MyParent.Cells[1].Text);
}
这里需要说明的是:上面这段代码只是为了说明如何使用NamingContainer关键字,其实,仅就本例而言,
要实现显示指定单元格文本内容不需要这么复杂,还有其他更简便的方式。
四、后续链接
就数据控件这个重点,后面,将推出《如何:定位数据控件的单元格》作为这两篇文章的姊妹篇,以系统阐述
数据控件的行列操作。