如何引用GridView的EmptyDataTemplate中的控件?代码调试求助
解决GridView EmptyDataTemplate中控件引用失败的问题
核心问题分析
你当前代码依赖e.Row.Cells(0).Controls(1)这种索引方式定位控件,这是不可靠的。ASP.NET在渲染模板时,会自动把模板中的空格、换行符转换为LiteralControl,导致Controls集合的索引位置随时可能变化,无法稳定定位到目标Panel。
修正方案
直接通过e.Row.FindControl()方法查找控件即可,因为EmptyDataTemplate中的控件的命名容器就是EmptyDataRow本身,无需通过Cells和Controls索引绕路:
If e.Row.RowType = DataControlRowType.EmptyDataRow Then Dim fi As New FileInfo(Server.MapPath("../../Comun/Varios/default1.aspx")) strcondicion = ViewState("condicion" & strtabla) If strcondicion IsNot Nothing Then Dim inttotalregistros As Integer inttotalregistros = Numeromaximoregistros(strtabla, True) s.Caption = "0 de " & Format(inttotalregistros, "n0") & " " & IIf(inttotalregistros <> 1, "registros", "registro") If strtabla = "tiposobras" Then ' 直接从EmptyDataRow查找控件 Dim pnlNoHayReg As Panel = CType(e.Row.FindControl("pnlnohayregistros"), Panel) Dim pnlAnadir As Panel = CType(e.Row.FindControl("pnlanadir"), Panel) ' 增加空值判断,避免空引用异常 If pnlNoHayReg IsNot Nothing Then pnlNoHayReg.Visible = False End If If pnlAnadir IsNot Nothing Then pnlAnadir.Visible = True End If End If Else cphcontenido.FindControl("pnlbusqueda" & strtabla).Visible = False s.Caption = "" End If End If
额外排查点
- 确认
strtabla变量的值确实等于"tiposobras",可通过断点调试验证。 - 确保GridView的
RowDataBound事件已正确绑定(在ASPX页面的GridView标签中添加OnRowDataBound="GridView_RowDataBound",或在后台代码中注册事件)。 - 如果依然无法找到控件,可使用递归查找控件的辅助方法,确保穿透所有命名容器:
Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control If root.ID = id Then Return root End If For Each c As Control In root.Controls Dim foundControl As Control = FindControlRecursive(c, id) If foundControl IsNot Nothing Then Return foundControl End If Next Return Nothing End Function
调用方式:
Dim pnlAnadir As Panel = CType(FindControlRecursive(e.Row, "pnlanadir"), Panel)
内容的提问来源于stack exchange,提问作者volar.2016
相关产品推荐
相关产品推荐

