怎样获取获取GridView里面的label
GridView如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="errornum" HeaderText="错误数" /> //control[0]
<asp:BoundField DataField="rightnum" HeaderText="正确数" /> //controls[1]
<asp:BoundField DataField="adatatime" HeaderText="答题时间" /> //control[2]
<asp:TemplateField HeaderText="正确率"> //control[3]
<ItemTemplate>
<asp:Label ID="bfb" runat=server>aa</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<Columns>
<asp:BoundField DataField="errornum" HeaderText="错误数" /> //control[0]
<asp:BoundField DataField="rightnum" HeaderText="正确数" /> //controls[1]
<asp:BoundField DataField="adatatime" HeaderText="答题时间" /> //control[2]
<asp:TemplateField HeaderText="正确率"> //control[3]
<ItemTemplate>
<asp:Label ID="bfb" runat=server>aa</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
我们现在要在 GridView1_RowDataBound(object sender, GridViewRowEventArgs e)事件中获取
<asp:Label ID="bfb" runat=server>aa</asp:Label>的引用
代码如下:
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
2 {
3 if (e.Row.RowType == DataControlRowType.DataRow)
4 {
5 Label bfb = (Label)e.Row.Controls[3].FindControl("bfb");
6
7 }
8
9 }
2 {
3 if (e.Row.RowType == DataControlRowType.DataRow)
4 {
5 Label bfb = (Label)e.Row.Controls[3].FindControl("bfb");
6
7 }
8
9 }
上面的第五行代码 Label bfb = (Label)e.Row.Controls[3].FindControl("bfb");
也可以改为 Label bfb = (Label)e.Row.Controls[3].Controls[1];
因为
<asp:TemplateField HeaderText="正确率"> </asp:TemplateField>
包含
-System.Web.UI.LiteralControl //controls[0]
-System.Web.UI.WebControls.Label //controls[1]
-System.Web.UI.LiteralControl //control[2]
三个子控件,所以label 的index为1。
包含
-System.Web.UI.LiteralControl //controls[0]
-System.Web.UI.WebControls.Label //controls[1]
-System.Web.UI.LiteralControl //control[2]
三个子控件,所以label 的index为1。