Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a TemplateField column in a GridView

How can I hide a TemplateField column in a GridView?

I tried the following:

<asp:TemplateField ShowHeader="False" Visible='<%# MyBoolProperty %>' >
<ItemTemplate>
    <asp:LinkButton ID="attachmentButton" runat="server" ... />
</ItemTemplate>

but it didn't work and gives the following error:

Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.TemplateField does not have a DataBinding event.

I tried also to hide it programmatically, but seems it's not possible to get a column by the name because there iss no name for TemplateField column.

like image 758
Homam Avatar asked Feb 10 '11 08:02

Homam


3 Answers

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
         e.Row.Cells[columnIndex].Visible = false;
}


If you don't prefer hard-coded index, the only workaround I can suggest is to provide a HeaderText for the GridViewColumn and then find the column using that HeaderText.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    ((DataControlField)UsersGrid.Columns
            .Cast<DataControlField>()
            .Where(fld => fld.HeaderText == "Email")
            .SingleOrDefault()).Visible = false;
}
like image 108
naveen Avatar answered Oct 16 '22 04:10

naveen


For Each dcfColumn As DataControlField In gvGridview.Columns
    If dcfColumn.HeaderText = "ColumnHeaderText" Then
        dcfColumn.Visible = false                    
    End If
Next
like image 29
Deepak Mishra Avatar answered Oct 16 '22 04:10

Deepak Mishra


If appears to me that rows where Visible is set to false won't be accessible, that they are removed from the DOM rather than hidden, so I also used the Display: None approach. In my case, I wanted to have a hidden column that contained the key of the Row. To me, this declarative approach is a little cleaner than some of the other approaches that use code.

<style>
   .HiddenCol{display:none;}                
</style>


 <%--ROW ID--%>
      <asp:TemplateField HeaderText="Row ID">
       <HeaderStyle CssClass="HiddenCol" />
       <ItemTemplate>
       <asp:Label ID="lblROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:Label>
       </ItemTemplate>
       <ItemStyle HorizontalAlign="Right" CssClass="HiddenCol" />
       <EditItemTemplate>
       <asp:TextBox ID="txtROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:TextBox>
       </EditItemTemplate>
       <FooterStyle CssClass="HiddenCol" />
      </asp:TemplateField>
like image 8
Chad Avatar answered Oct 16 '22 03:10

Chad