iadducchio3 iadducchio3 - 9 months ago 52
ASP.NET (C#) Question

set conditional visibility of templated field textbox in ASP.NET markup

I want the textbox in the templated field to be visible only if it contains text.
The textbox text is bound to my datasource but I can't access the textbox itself
from within the server tags because it is in a templated field. I tried to do the
following but I get index out of range when indexing the gridview(which makes sense).
Is there any other way to do this? or do i need to loop though the gridview
textboxes in the code behind? Thanks in advance!

<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="Textbox1" runat="server" Text='<%# Eval("Quantity") %>'
visible= '<%# String.IsNullOrEmpty(DirectCast(Gridview1.Rows(Container.DisplayIndex).FindControl("Textbox1"), TextBox).Text) %>'>
</asp:TextBox>
</ItemTemple>
</TemplateField>

Answer Source

You can do this with a Ternary Operator

<asp:TextBox ID="Textbox1" runat="server" Text='<%# Eval("Quantity") %>
     Visible='<%# string.IsNullOrEmpty(Eval("Quantity").ToString()) ? false : true %> />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download