1. 程式人生 > >C# 動態生成GridView的列

C# 動態生成GridView的列

http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2008430/112166.html

想實現這樣的功能嗎?在程式執行中使GridView動態生成列,而並不是將列固定寫死在GridView上

寫個繫結GrideView的方法

    /**//// <summary>
    /// 繫結生成GridView
    /// </summary>
    /// <param name="gdv">要繫結的GridView</param>
    /// <param name="dtblDataSource">GridView的資料來源</param>
    /// <param name="strDataKey">GridView的DataKeyNames</param>
    public static void GridViewBind(GridView gdv, DataTable dtblDataSource, string strDataKey)
    {
        gdv.Columns.Clear();

        gdv.AutoGenerateColumns = false;
        gdv.DataSource = dtblDataSource;
        gdv.DataKeyNames = new string[] ...{ strDataKey };

        for (int i = 0; i < dtblDataSource.Columns.Count; i++)   //繫結普通資料列
        {
            BoundField bfColumn = new BoundField();
            bfColumn.DataField = dtblDataSource.Columns[i].ColumnName;
            bfColumn.HeaderText = dtblDataSource.Columns[i].Caption;
            gdv.Columns.Add(bfColumn);
        }

        gdv.Columns[1].Visible = false;

        CommandField cfModify = new CommandField();  //繫結命令列
        cfModify.ButtonType = ButtonType.Button;
        cfModify.SelectText = "修改";
        cfModify.ShowSelectButton = true;
        gdv.Columns.Add(cfModify);

        gdv.DataBind();
    }
只要呼叫這個方法就可以啦!試試吧!


文章出處:http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2008430/112166.html