GridView动态添加列的实现代码

发布时间:2020-05-15编辑:脚本学堂
gridview如何动态添加列呢?请参考本文给出的代码吧。

gridview动态添加列,完整代码如下。
 

复制代码 代码示例:

public class MyTemplate:ITemplate
{
    private string strColumnName;
    private DataControlRowType dcrtColumnType;

    public MyTemplate(string strColumnName, DataControlRowType dcrtColumnType)
    {
this.strColumnName = strColumnName;
this.dcrtColumnType = dcrtColumnType;
    }

    public void InstantiateIn(Control ctlContainer)
    {
switch (dcrtColumnType)
{
    case DataControlRowType.Header: //列标题
    Literal ltr = new Literal();
    ltr.Text = strColumnName;
    ctlContainer.Controls.Add(ltr);
    break;

    case DataControlRowType.DataRow: //模版列内容——加载hyperlink1
HyperLink hl = new HyperLink();
hl.ID = "hyperlink1";
hl.NavigateUrl = "erro.aspx";
hl.Text = "asddddd";
ctlContainer.Controls.Add(hl);
break;
}

    }

}
GridView gdview = new GridView();// (GridView)m_map.Page.FindControl("GridView1");
gdview.AutoGenerateColumns = false;
gdview.DataKeyNames = new string[] { "SDE.ST_ZD.ZD_DJH" };

BoundField bf1 = new BoundField();
BoundField bf2 = new BoundField();
TemplateField tf = new TemplateField();

bf1.HeaderText = "地籍号";

bf1.DataField = "SDE.ST_ZD.ZD_DJH";

bf1.readonly = true;

bf2.HeaderText = "权利人名称";
bf2.DataField = "SDE.ST_ZD.QLR_MC";

tf.HeaderText = "模板列测试";
tf.ItemTemplate = new MyTemplate("aaaa", DataControlRowType.DataRow);

CommandField cf = new CommandField();

cf.ButtonType = ButtonType.Button;

cf.ShowCancelButton = true;

cf.ShowEditButton = true;

gdview.Columns.Add(bf1);

gdview.Columns.Add(bf2);

gdview.Columns.Add(tf);