Javascript – Control gridview column visibility using javascript

asp.netgridviewjavascript

I have a gridview and I have to control the visiblitiy of the grid columns using javascript. Consider this gridview. I have a few columns.

<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="False" Width="100%">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkResource" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Resource">
            <ItemTemplate>
               <asp:Label ID="Resource" Text='<%# Bind("Resource") %>' runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
               <asp:BoundField DataField="Description" HeaderText="Resource Description" HtmlEncode="false">
        <ItemStyle HorizontalAlign="Center" />
        <HeaderStyle HorizontalAlign="Center" />
    </asp:BoundField>

     </asp:TemplateField>
  </Columns>
</asp:GridView>

I can control the visibility of these columns at the server side by using this –

grdTest.Columns[n].Visible = false;

But, I have to control the visibility from the client side using javascript. I tried a lot but I was only able to access either the row object or any particular cell of the gridview.

grid.rows[index].cells[i].style="display: none"; //for cell

Is there a way to access the column object of the gridview and control its visibility using javascript?

Best Answer

You can try with calling server side code. Here is the js function that is used to call the code:

function HideColumns(sender, args)
{
    PageMethods.HideSomeColumns(args, onSuccess, onError);
}

function onReportSuccess(result)
{
}

function onReportError(error)
{
    alert("There was an error.");
}

And here is the server side function that is used to hide the columns that you want:

[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static void ReportTranslation(int n)
{
    grdTest.Columns[n].Visible = false;
}

There is other option for you - using pure js:

function show_hide_column(col_no, do_show) {

    var stl;
    if (do_show) stl = 'block'
    else         stl = 'none';

    var tbl  = document.getElementById('id_of_table');
    var rows = tbl.getElementsByTagName('tr');

    for (var row=0; row<rows.length;row++) {
      var cels = rows[row].getElementsByTagName('td')
      cels[col_no].style.display=stl;
    }
}