后台动态生成GridView列和模版

考虑到很多数据源是不确定的,所以这时无法在前台设置gridview的表头,需要在后台动态指定并绑定数据。

前台代码如下:

<%@ Page Title="主页" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
</div>
</asp:Content>

.cs页面代码如下

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }

/// <summary>
/// 绑定gridview
/// </summary>
    public void BindData()
    {
        string sqlcc = "SELECT * from Users";//order by gwbg.id desc
        DataTable dt = new DataTable();
        dt = DBHelp.ExecuteQueryWithoutParameter(sqlcc, CommandType.Text);
        GridView1.AutoGenerateColumns = false;//设置自动产生列为false
        GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing); //添加编辑事件
        GridView1.RowDeleting += new GridViewDeleteEventHandler(GridView1_RowDeleting);//添加删除事件
        GridView1.RowCancelingEdit += new GridViewCancelEditEventHandler(GridView1_RowCancelingEdit);//添加删除事件
        GridViewBind(GridView1, dt, "Id");
    }

    /// <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);
        }

        //添加编辑列
        CommandField cf = new CommandField();//命令字段
        cf.ButtonType = ButtonType.Link;//超链接样式的按钮
        cf.ShowEditButton = true;//显示编辑按钮
        cf.CausesValidation = false;//引发数据验证为false
        cf.HeaderText = "编辑";
        cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        gdv.Columns.Add(cf);//添加编辑按钮到gridview

        //添加删除列
        CommandField cf2 = new CommandField();
        cf2.ButtonType = ButtonType.Link;
        cf2.ShowDeleteButton = true;//显示删除按钮
        cf2.CausesValidation = false;
        cf2.HeaderText = "删除";
        cf2.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        gdv.Columns.Add(cf2);

        //添加包复选框的模板列
        TemplateField tf = new TemplateField();
        tf.ItemTemplate = new MyTemplate("", DataControlRowType.DataRow);
        //tf.HeaderText = "选择";
        tf.HeaderTemplate = new MyTemplate("模版列-选择框", DataControlRowType.Header);
        tf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        gdv.Columns.Add(tf);

        gdv.DataBind();//绑定

    }

    //删除gridview的行
    void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int i = e.RowIndex;
        MessageBox.Show(this, "删除ID为:"+GridView1.Rows[i].Cells [0].Text.ToString () );
    }

    //编辑行
    public void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int i = e.NewEditIndex;
        string id = GridView1.Rows[i].Cells[0].Text.ToString();
        MessageBox.Show(this, "删除ID为:" + id);
    }

    //取消
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindData();
    }

}

  其中,添加模版的MyTemplate类代码为:

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

    public MyTemplate()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 动态添加模版列
    /// </summary>
    /// <param name="strColumnName">列名</param>
    /// <param name="dcrtColumnType">列的类型</param>
    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: //模版列内容——加载CheckBox
                CheckBox cb = new CheckBox();
                cb.ID = "CheckBox1";
                cb.Checked = false;
                ctlContainer.Controls.Add(cb);
                break;
        }
    }

}

在MyTemplate类中,这里是直接写了添加CheckBox,其实我们可以在MyTemplate的构造函数里添加一个参数,表示传进来的要在模版里面添加的控件的类型。这样就可以根据

控件类型来自动生成控件了,而不要在类里面去手动写需要生成的控件。

其中效果图如下:

时间: 2024-10-29 04:16:25

后台动态生成GridView列和模版的相关文章

.NET 后台动态添加GridView列

1 BoundField bfColumn1 = new BoundField(); 2 bfColumn1.DataField = "zbcompanyname"; 3 bfColumn1.HeaderText = "中标供应商"; 4 this.GridView1.Columns.Add(bfColumn1);

后台动态生成静态select标签的option项

以下为代码示例: <select id="Category_<%#Eval("BTUserID") %>" name="Category_<%#Eval("BTUserID") %>" disabled on onchange=setHourlyCost("<%#Eval("BTUserID") %>") style="width:20

Silverlight系列--动态生成DataGrid列 根据动态列绑定Dictionary数据

1.获取表头数据源动态生成DataGrid表头 DataGridTextColumn d = new DataGridTextColumn(); d.Header = itemPriceClass.PriceKindCode + itemPriceClass.PriceKindName; Binding bin = new Binding(); bin.Converter = new RowIndexConverter(); bin.ConverterParameter = itemPriceC

ASP.NET动态生成GridView的使用

根据DataTable动态生成包含checkbox的GridView,其中DataTable中对应checkbox那一列的值必须为bool值. public static GridView DynamicGenerateColumns(GridView gv, DataTable dt) { // 把GridView的自动产生列设置为false,否则会出现重复列 gv.AutoGenerateColumns = false; // 清空所有的Columns gv.Columns.Clear();

WPF后台动态生成右键菜单

#region 循环生成右键菜单 private ContextMenu ContextMenus(Dictionary<string, RoutedEventHandler> list) { ContextMenu cm = new ContextMenu(); Style style = (Style)this.FindResource("ContextMenu"); //定义前台显示模板 cm.Style = style; foreach (var dc in lis

如何在后台动态生成ASPxCheckBoxList标签并循环(数据调用存储过程)

1 DataTable dt_attrname = new DataTable(); 2 DataTable dt_valuename = new DataTable(); 3 dt_valuename = goodsmanagebll.Get_AdminGetAttributeListandValues(_cateid).Tables[0]; //属性值 4 dt_attrname = goodsmanagebll.Get_AdminGetAttributeListandValues(_cat

asp.net动态添加GridView的模板列,并获取列值

一.动态添加模板列: 1.建立模板列样式: 说明:下边代码可以直接写在aspx文件中,也可以单独建立cs文件:另外,我没有写button.linkButton等控件,意思差不多,不过当需要添加事件时,记得将事件名称传入,并附加在控件上 public class GridViewTemplate : ITemplate{ /// <summary> /// 模板类型:标题或内容: /// DataControlRowType.Header和DataControlRowType.DataRow /

C#后台动态添加Grid表格

前面页面: 1 <ScrollViewer x:Name="sv_data" Grid.Row="1" BorderBrush="#25A0DA" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"> 2 3 <Grid x:Name="rgv_schedule" Backgro

datagrid动态生成列并动态赋值

这周接到的任务是动态生成某datagrid的标题,并且要能够根据动态生成的标题来再去数据库中找到相应的值并拼接赋值上去. 项目经理给我的静态页面如下: 左边一列为车型,右边的上面是零件号,下面是固定的,直接循环生成就行,但是数量不一定,需要动态生成.里面的数据是自动加载的. 后台数据库中能够得到的数据大概是这个形式: 这个问题的难点如下: 1.动态生成datagrid的column. 2.将SQL拿出来的数据拼接成前台需要的横行形式,也就是列转行. 先说下解决的思路和方法. 首先是datagri