Reputation: 31
This the templatefield
that is column 10 in the Gridview
:
<asp:TemplateField>
<HeaderTemplate>
<asp:Label runat="server">Active Licenses</asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblActiveCodes" runat="server" Text='intValues'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is where it is referred to in a foreach
loop.
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.Cells[10].Text.Equals(0))
{
row.Visible = false;
}
}
So it is column 10 in the GridView
and I'm looking to make the cells with value 0 invisible. intValues
are int
, that come from the database. gvCustomers
is the ID
of my GridView
.
How come row.Cells[10]
doesn't work, but more importantly, how can we make it work?
Upvotes: 2
Views: 1151
Reputation: 2498
Add double quote to zero. Text type is string.
if ((row.Cells[10].FindControl("lblActiveCodes") as Label).Text.Equals("0"))
Upvotes: 1
Reputation: 56716
Many issues here.
First, to bind a column to a label text you need to use Eval, what you have currently is just a text "intValues" literally. So:
Text='<%# Eval("intValues") %>'
Second, label is a server-side control. Cell will contain a control, not a simple text. So you should be looking for this control. By the way, you can do that for the whole row, so no need to count the column index:
Label label = row.FindControl("lblActiveCodes") as Label;
Third, once value is bound to a label text it is now a string. If column value was not a string, it will be converted to one with ToString call. So:
if (label != null && label.Text != "0")
{
row.Visible = false;
}
Last but not least, you did not mention when you are running this code. It won't always work, grid view has to be data bound already. The best time to run something like that would be RowDataBound event, in which case you do not need to iterate over the rows and also you have 100% guarantee that grid view is data bound and all controls are created.
Upvotes: 1