GridView:如何隐藏模板字段列动态
问题描述:
我有一个带有模板字段的gridview。 gridview中的最后一行是可以是正数或string.empty(= null)的总计行。这个想法如下:当总计行= null时,我怎么能隐藏gridview的一列? 效果应该是只有具有值的列可见。因为每次这是一个动态过程,输入(即一年)可能不同。 一个模板领域的例子:GridView:如何隐藏模板字段列动态
<asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:LinkButton ID="H3" runat="server" ToolTip="Milano-Sanremo" CommandName="Sort" CommandArgument="Milaan-San Remo DESC" Text="MSR" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="R3" runat="server" ToolTip="Milano-Sanremo" Text='<%# Eval("Milaan-San Remo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
我试图隐藏列在代码隐藏的方式:
Dim TotalColumns As Integer
TotalColumns = GridView1.Rows(0).Cells.Count()
For i As Integer = 0 To TotalColumns - 1
If i > 4 Then
For Each row As TableRow In GridView1.Rows
If row.Cells(2).Text = "Nmbr of Riders" Then
Dim lid As String = DirectCast(row.FindControl("R3"), Label).Text
If lid = String.Empty Then
GridView1.Columns(i).Visible = True
Else
GridView1.Columns(i).Visible = False
End If
End If
Next
End If
Next
文本“骑士NMBR”表示汇总行。 R3对应于上面的模板字段。该代码位于GridView的DataBound事件中。 我尝试了许多其他解决方案,但似乎没有任何帮助。它看起来像asp.net没有在表格单元格中看到任何值,但也许我错了。 任何帮助将不胜感激!
答
检查GridView数据源。在DataBind()之后,隐藏该列。
GridView1.DataSource = dataSource;
GridView1.DataBind();
// Hide last column
GridView1.Colums[GridView1.Columns.Count - 1].Visible = dataSource.Any(c => c.Nbmr > 0);
我不知道你的数据源结构。条件可以根据你的数据源而改变。