首页 > 解决方案 > 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 事件处理程序之前触发。

标签: asp.netvb.net

解决方案


您必须检查 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 属性是立即设置的。


推荐阅读