asp.net - GridView 行 FindControl(x) 文本为空白
问题描述
我有一个 GridView,我想在价格为 0 时隐藏一些行。当我尝试检查值时,我得到所有行的空白字符串。
标记:为了便于阅读,已删除不相关的行。getProductInfo 和 getPrice 是接收和返回字符串的查找函数
<asp:GridView ID="gvRebuild" runat="server" AutoGenerateColumns="false" Width="100%" OnRowDataBound="gvRebuild_RowDataBound">
<Columns>
<asp:BoundField ... />
<asp:TemplateField ... />
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" ItemStyle-Width="12%">
<ItemTemplate>
<asp:Label runat="server" ID="price" ><%# getPrice(getProductInfo(Eval("fieldName")))%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ... />
</Columns>
</asp:GridView>
代码背后:
Protected Sub gvRebuild_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim p As Label = e.Row.FindControl("price")
If p IsNot Nothing Then
Debug.Print(String.Format("*{0}*", p.Text))
If p.Text = "$0.00" Then
e.Row.Visible = False
End If
End If
End Sub
调试语句确认在“价格”控件中找到的所有值都是空白的。我还通过调试器确认 getPrice 函数返回正确的值并在每行的 RowDataBound 事件处理程序之前触发。
解决方案
您必须检查 RowType。第一行将是标题行。标题行不包含文本框,因此出现 NULL 错误。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//use findcontrol here
}
}
VB
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If (e.Row.RowType = DataControlRowType.DataRow) Then
'use findcontrol here
End If
End Sub
更新
我明白你现在的意思了。它是 NULL 值而不是控件本身。我做了一些测试,结果发现如果你使用你的方法它不起作用。但是把它改成这个,它会的。
<asp:Label runat="server" ID="price" Text='<%# getPrice(getProductInfo(Eval("fieldName"))) %>'></asp:Label>
似乎标签内的数据绑定是在行或网格视图完成后完成的,但 Text 属性是立即设置的。
推荐阅读
- c# - 为按钮单击添加多个用户控件
- android - Ionic 启动画面后的白屏
- android - 用于指定依赖版本号的 Gradle build.gradle 代码样式
- python - 使用 Django 在 SQLite 中遇到问题
- javascript - 如何为“触摸”事件制作“鼠标离开”模拟?
- powershell - 从列中获取唯一元素返回一个值
- google-sheets - 我对谷歌表格中的 VLOOKUP 公式有疑问
- spring-boot - 使用 Gradle 将 ZIP 文件复制到没有任何元数据的 Artifactory
- ldap - ldaptor 框架 ProxyBase use_tls 属性似乎不起作用
- powerbi-embedded - Power BI Embedded - 使用 Javascript 获取当前筛选器