How to hide DataGrid Column? How to hide GridView Column?

from:http://www.netomatix.com/development/GridViewHideColumn.aspx
Often times you want to hide the columns in grid view. Some times you want to hide the column completely meaning you do not want the information to be rendered on the page at all. And there are times when you want the data for that column to be rendered on the page but not visible to user.

If you do not want to render the column at all, then you can set Visible property for that column to False. You can set this attribute value in ASPX page or you can set it from code behind. The following snippet shows how it is set on ASPX page.

<columns>
    <asp:boundfield datafield="ProductID" visible=False />
    <asp:boundfield datafield="Name" headertext="Product Name" />
    <asp:boundfield datafield="ProductNumber" headertext="Product Number" />
</columns>

Now if you want to render the column data but want to hide it from the user, then using Visible property will not work because setting that property will remove the column from the grid altogether. You can accomplish hiding the column by setting a style on the column that sets visibility style to hidden. You can set this at design time or run time.

<style type="text/css">
    .hiddencol
    {
        display:none;
    }
    .viscol
    {
        display:block;
    }
</style>

<columns>
    <asp:boundfield datafield="ProductID" itemstyle-cssclass="hiddencol" />
    <asp:boundfield datafield="Name" headertext="Product Name" />
    <asp:boundfield datafield="ProductNumber" headertext="Product Number" />
</columns>

If you want to switch the visibility of column at run time or programmatically then you can do it in RowCreated event of the grid view.

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         e.Row.Cells[0].CssClass = "hiddencol";
     }
     else if (e.Row.RowType == DataControlRowType.Header)
     {
         e.Row.Cells[0].CssClass = "hiddencol";
     }
}

And you access the values in these hidden columns you can use the technique that I discussed in previous article How to access gridview cell values on client side

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s