如何知道GridView的ItemTemplate中的服务器控件的id?

时间:2011-06-28 23:21:14

标签: c# asp.net gridview

问题:如何将FixHyperLink的可见性绑定到Label1具有非空文本值的条件?

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
    <Columns>
        <asp:TemplateField HeaderText="Error" SortExpression="Error">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Error") %>'></asp:Label>
                <asp:HyperLink ID="FixHyperLink" runat="server" NavigateUrl='<%# Bind("AppID", "~/da/Default2.aspx?appid={0}") %>'>Fix</asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

更新:答案的C#版本

        foreach (GridViewRow row in GridView1.Rows)
        {
            var l = (Label)row.FindControl("Label1");
            var h = (HyperLink)row.FindControl("FixHyperLink");
            h.Visible = !string.IsNullOrWhiteSpace(l.Text);
        }

2 个答案:

答案 0 :(得分:2)

您必须确定要更改的行的索引,然后按以下方式进行:

        Dim tempRow As System.Web.UI.WebControls.GridViewRow
    Dim tempLabel As Label
    Dim tempHyperlink As HyperLink

    For Each tempRow In GridView1.Rows
        tempLabel = CType(tempRow.FindControl("Label1"), Label)
        tempHyperlink = CType(tempRow.FindControl("FixHyperLink"), HyperLink)
        If tempLabel.Text.Trim <> String.Empty Then
            tempHyperlink.Visible = True
        Else
            tempHyperlink.Visible = False
        End If
    Next

答案 1 :(得分:2)

您可以添加“ Visible ='&lt;%#String.IsNullOrEmpty((string)Bind(”Error“))?false:true; ”超链接标记

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
<Columns>
    <asp:TemplateField HeaderText="Error" SortExpression="Error">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Error") %>'></asp:Label>
            <asp:HyperLink ID="FixHyperLink" runat="server" NavigateUrl='<%# Bind("AppID", "~/da/Default2.aspx?appid={0}"%>') %>' Visible='<%# String.IsNullOrEmpty((string)Bind("Error")) ? false:true; %>' >Fix</asp:HyperLink>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>