Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make gridview column visible true or false dynamically?

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

like image 210
Raghuveera Avatar asked Nov 28 '13 07:11

Raghuveera


3 Answers

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">
like image 150
Bhavesh Kachhadiya Avatar answered Sep 16 '22 20:09

Bhavesh Kachhadiya


Here is the simple answer. Create css as below

.classHide{ display:none } 

then instead of column.visible = false, just assign classHide CSS class to the column.

e.g.

grdRole.Columns(0).ItemStyle.CssClass = "classHide"
    grdRole.Columns(0).HeaderStyle.CssClass = "classHide"
like image 27
Indranil.Bharambe Avatar answered Sep 19 '22 20:09

Indranil.Bharambe


*strong text*Try to make use of the event ItemDataBound event and try the following syntax to hide the column dynamically:

   mygrid.Columns[1].Visible = false           //(Example)

Column count for a datatable starts from 0 not from 1 . so if it is the second column , you want to hide, index should be 1.

Hope this helps..

like image 39
Sai Avinash Avatar answered Sep 18 '22 20:09

Sai Avinash