2014年1月21日

隱藏Gridview列表之標題列中某特定欄位及該隱藏特定欄位整列

隱藏Gridview列表之標題列中某特定欄位及該隱藏特定欄位整列
使用 OnRowCreated="GridView1_RowCreated" ,在Row create再指定要隱藏。


 .aspx


.aspx.cs

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //隱藏標題列中某特定欄位及該隱藏特定欄位整列
        //法一
        GridView1.Columns[2].Visible = false;
        //法二
        foreach (DataControlField col in GridView1.Columns)
        {
            if (col.HeaderText == "標題文字3")
            {
                col.Visible = false;
            }
        }
        //法三(using System.Linq;)
        ((DataControlField)GridView1.Columns
                .Cast()
                .Where(fld => fld.HeaderText == "標題文字3")
                .SingleOrDefault()).Visible = false;


    }

隱藏標題列中某特定欄位
使用 OnRowDataBound="GridView1_RowDataBound",資料都好了,再隱藏欄位。 

.aspx.cs
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //隱藏標題列中某特定欄位
            //法一
            e.Row.Cells[3].Visible = false;
            //法二
            foreach (TableCell col in e.Row.Cells)
            {
                if ((((System.Web.UI.WebControls.DataControlFieldCell)(col)).ContainingField).HeaderText == "標題文字4")
                {
                    col.Visible = false;
                }
            }
            //法三
            foreach (DataControlFieldCell col in e.Row.Cells)
            {
                if ((col.ContainingField).HeaderText == "標題文字4")
                {
                    col.Visible = false;
                }
            }

            //法四(using System.Linq;)
            e.Row.Cells.Cast()
               .Where(c => c.Text == "標題文字4")
               .ToList()
               .ForEach(col => col.Visible = false);

        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

        }


    }

Study:
GridView 的 OnRowDataBound="GridView1_RowDataBound" 及OnRowCreated="GridView1_RowCreated" 的差異。

Ref:
http://stackoverflow.com/questions/4954871/how-to-hide-a-templatefield-column-in-a-gridview
http://www.dotblogs.com.tw/dennismao/archive/2009/08/10/9977.aspx


沒有留言: