一、应用场景
在使用GridView、Repeater、DataList等数据容器时,往往会在其模板列,即:<ItemTemplate></ItemTemplate>
中添加其他控件,如:Label、RadioButtonList、CheckBoxList等控件。那么,此后,我们在编辑过程中,不能
再直接用这些控件的ID来引用他们。原因是,这些控件会在每个纪录行中重复使用,原来在UI部分定义的Id在整
个容器中不再唯一。所以,便不能用这些控件在UI部分定义的Id来引用他们。
那么,如何实现这些控件的访问呢?
二、技术实现
1、方法一:使用FindControl()方法来引用控件。如下,以DataList中的Label控件为例。
在该例中Label控件位于DataList的模板列中,此时,在编程模式下,以Label的Id值Cash来
引用Label,如:Cash.Text,则系统提示:上下文不存在Cash。那么,此时,可以用
FindControl()方法来查找Label,如:本例为:FindControl("Cash"),来查找控件Label,
然后,再引用该控件的属性或方法。本例UI部分具体如下:
<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>
以编程方式引用Cash标签具体步骤为:
(1)、在DataList中的每条纪录项Items[Index](其中,Idex为纪录序号)中使用FindControl("Cash")
查找Cash标签控件。
如:本例为:DataList1.Items[i].FindControl("Cash"),具体程序如下:
for (int i=0;i<=DataList1.Items.Count-1;i++)
{
Label My_Label=(Label)DataList1.Items[i].FindControl("Cash");
}
(2)通过被赋原控件值的新控件(本例为:My_Label)来引用控件(本例为:Cash)的属性。具体如下:
My_Label.Text = “我是被查找Label,Id=Cash”;
那么,通过以上两步便实现了对容器DataList控件中的Lable控件(Id="Cash")的引用。
但,注意:GridView控件的纪录项引用为Rows[Index],如:GridView.Rows[2].FindControl("Cash")
而Repeater、DataList控件均为Items[index]。
2、方法二:使用Controls[]数组来引用控件。
即:以每个纪录行(Item)中控件(Control[Index])数组元素的形式引用控件。
如上例,也可使用:DataList1.Items[i].Controls[1],因为在上例中Controls[0]为Table,所以,Label为Controls[1]。
同样,GridView为:GridView.Rows[i].Controls[1].
三、总结提高
上例编程的最后结果为:
for (int i=0;i<=DataList1.Items.Count-1;i++)
{
Label My_Label=(Label)DataList1.Items[i].FindControl("Cash");
My_Label.Text = “我是被查找Label,Id=Cash”;
}
或:
for (int i=0;i<=DataList1.Items.Count-1;i++)
{
Label My_Label=(Label)DataList1.Items[i].Controls[1];//注(Label),为显式类型转换
My_Label.Text = “我是被查找Label,Id=Cash”
}
这样,便实现了以编程方式对数据容器下的控件Label的引用,然后,便可以读/写Label控件的属性,
或使用Label控件的方法。其他如: RadionButtonList、CheckBoxList控件在数据容器中的引用与本例
Label控件的引用类似。
四、后续链接
以上两种法是关于容器中控件的引用技术实现说明,下一篇,将着重讨论关于控件之上命名容器的访问。