Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding a GridView ID column

Tags:

c#

.net

asp.net

Seems to be a common issue.

I'm trying to hide a column of my GridView. I have read that simply setting the column to 'visible = false' will not work as I'm auto-generating my data.

Currently my code stands as so:

 protected void Page_Load(object sender, EventArgs e)
    {
        bind();

        if (GridView1.Columns.Count > 0)
            GridView1.Columns[0].Visible = false;
        else
        {
            GridView1.HeaderRow.Cells[0].Visible = false;
            foreach (GridViewRow gvr in GridView1.Rows)
            {
                gvr.Cells[1].Visible = false;
            }
        }

    }

The 'if' statement will not trigger as as said I am auto-generating the data. With the above loop, I can hide the header text of the column but want to hide the whole column with the ability to still be able to access the hidden data.

like image 942
user1352057 Avatar asked Dec 12 '25 09:12

user1352057


2 Answers

How about just doing this later in the control's life cycle (when the Columns collection has been populated):

protected void GridView1_PreRender(object sender, EventArgs e)
{
    if (GridView1.Columns.Count > 0)
        GridView1.Columns[0].Visible = false;
    else
    {
        GridView1.HeaderRow.Cells[0].Visible = false;
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            gvr.Cells[1].Visible = false;
        }
    }
}

Note: you would need to add OnPreRender="GridView1_PreRender" to your GridView markup.

like image 122
Josh Darnell Avatar answered Dec 13 '25 23:12

Josh Darnell


Why not use the GridView.DataKeyNames and GridView.DataKeys properties to store the ID and then retrieve it with the rowIndex later? This also will keep the column from being autogenerated.

DataKeyNames

DataKeys

like image 38
Ceres Avatar answered Dec 13 '25 23:12

Ceres