How to hide a TemplateField column in a GridView

前端 未结 9 1819
遇见更好的自我
遇见更好的自我 2020-12-03 04:13

How can I hide a TemplateField column in a GridView?

I tried the following:



        
相关标签:
9条回答
  • 2020-12-03 05:17

    Am I missing something ?

    If you can't set visibility on TemplateField then set it on its content

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

    or if your content is complex then enclose it into a div and set visibility on the div

    <asp:TemplateField>
      <ItemTemplate>
        <div runat="server" visible='<%# MyBoolProperty  %>' >
          <asp:LinkButton ID="attachmentButton" runat="server" ... />
        </div>
      </ItemTemplate>
    </asp:TemplateField> 
    
    0 讨论(0)
  • 2020-12-03 05:18
    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;
    }
    
    0 讨论(0)
  • 2020-12-03 05:18

    A slight improvement using column name, IMHO:

        Private Sub GridView1_Init(sender As Object, e As System.EventArgs) Handles GridView1.Init
        For Each dcf As DataControlField In GridView1.Columns
            Select Case dcf.HeaderText.ToUpper
                Case "CBSELECT"
                    dcf.Visible = Me.CheckBoxVisible
                    dcf.HeaderText = "<small>Select</small>"
            End Select
        Next
    End Sub
    

    This allows control over multiple column. I initially use a 'technical' column name, matching the control name within. This makes it obvious within the ASCX page that it's a control column. Then swap out the name as desired for presentation. If I spy the odd name in production, I know I skipped something. The "ToUpper" avoids case-issues.

    Finally, this runs ONE time on any post instead of capturing the event during row-creation.

    0 讨论(0)
提交回复
热议问题