2013年7月31日 星期三

[ASP.NET] 取得GridView隱藏cell的值

說明:在GridView繫結欄位若設定屬性Visible="false",無法在code behind取得值。

作法:因為GridView事件載入順序是DataBinding->RowCreated->RowDataBound->DataBound,所以在RowCreated與RowDataBound事件內隱藏欄位,還是可以取得cell的值。

protected void GridView_RowCreated(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
    {
        //要隱藏的欄位
        e.Row.Cells[0].Visible = false;  
    }      
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            //要隱藏的欄位
            e.Row.Cells[0].Visible = false;
        }
    }