Gridview column made hide/show makes the column empty - c#

166 Views Asked by At

My Grid view have three columns. First column has HeaderTemplate. Initially last two column is invisible. When clicking on the header of first column the near two column should show/hide respectively. I have done this. But the problem is the value of column got empty when expanding it. Please suggest.

      <asp:TemplateField>
      <HeaderTemplate>
      Student  <asp:ImageButton ID="btn_expand" runat="server" ImageUrl="images/plus.png" OnClick="btn_expand_Click"/>
      </HeaderTemplate>
                  <ItemTemplate>
                      <asp:Label ID="lbl_name" runat="server"/>
                  </ItemTemplate>
                </asp:TemplateField>
            <asp:BoundField DataField="fname" Visible="false"  HeaderText="Name" />  
               <asp:BoundField DataField="frole"   Visible="false"   HeaderText="Role" />  
    
   

  protected void btn_expand_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton img = (ImageButton)sender;
        if (img.ImageUrl == "images/plus.png")
        {
            img.ImageUrl = "images/minus.png";
            Gridview1.Columns[1].Visible = true;
            Gridview1.Columns[2].Visible = true;
        }
        else
        {
           img.ImageUrl = "images/plus.png";
           Gridview1.Columns[1].Visible = false;
           Gridview1.Columns[2].Visible = false;
        }
    }
1

There are 1 best solutions below

0
RS Patel On

1)Remove Visible=false attribute from the column in .aspx file

2)To hide the column use RowCreated or RowDataBound event of grid view in .cs file

Ex.

     protected void <GridviewID>_RowCreated(object Sender,GridViewRowEventArgs e)
     {
           e.Row.Cells[index].Visible = false;
     }