How to make gridview column visible true or false dynamically?

asp.net, c#, gridview

Solution

This is perfect solution for dynamically generated columns in gridview

Please try this :

int indexOfColumn = 1; //Note : Index will start with 0 so set this value accordingly
protected void mygrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.Cells.Count > indexOfColumn)
    {
        e.Row.Cells[indexOfColumn].Visible = false;
    } 
}      

For .aspx page edit gridview tag as follow :

 <asp:GridView ID="mygrid" runat="server" AllowPaging="True" 
       onpageindexchanging="mygrid_PageIndexChanging" PageSize="15" 
       PersistedSelection="true"  
       ondatabound="mygrid_DataBound"
       OnRowDataBound="mygrid_RowDataBound">

Problem

I am using GridView in asp.net like this: ``` mygrid.DataSource = dTable; mygrid.DataBind(); if (mygrid.Columns.Count > 1) { mygrid.Columns[2].Visible = false; } ``` my grid view code is as follows ``` <asp:GridView ID="mygrid" runat="server" AllowPaging="True" onpageindexchanging="mygrid_PageIndexChanging" PageSize="15" PersistedSelection="true" ondatabound="mygrid_DataBound"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:HyperLink ID="Edit" runat="server" Text="Edit" NavigateUrl='<%# Eval("Value", "~/myweppage.aspx?Id=M{0}") %>' /> </ItemTemplate> </asp:TemplateField> </Columns> <PagerSettings PageButtonCount="4" /> </asp:GridView> ``` Here I am not able to set `visible=false`. I tried with the following answer How do I make several gridview columns invisible dynamically? I am not finding `datarow` event in Visual Studio 2010. Can anyone help me to set the column visible property? my Column structure of data table is column[0] is `Value` column then 4 other columns are there. my Column structure of Grid view is column[0] is `link field` column1 is `Value field from Dtable` 4 other columns

Original source