[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

你可能感兴趣的:(GridView)