GridView 动态绑定列

GridView1.DataSource = BLL.GetDataItem();//获取数据
        //创建好的GridView中移除某个列:
        //GridView1.Columns.RemoveAt(1); 
        //在创建好的GridView中添加一列:
        //构造一个数据列对象出来
        BoundField column = new BoundField();
        column.HeaderText = "第二列";
        //column.SortExpression = "date1";//指定排序的字段
        column.DataField = "date1";//数据字段名称(类的属性)
        //加此数据列进入GridView
        //GridView1.Columns.Add(column);
        //----或者插入到指定位置
        GridView1.Columns.Insert(1, column);//插在第一列后(显示在第二列)
        GridView1.DataBind();

在sq查询l的时候只需要把所有数据查询出来,用此方法动态绑定即可.如果使用Insert方法插入动态列之后,GridView里的控件都被清空了,只留下了直接绑定的Text值,将GridView的EnableViewState设为False.

上例是用BoundField加入到集合中.若要将 TemplateField 动态加入GridView ,需要建立新的 TemplateField 、定义适当样板,然后将TemplateField 加入到集合Columns 中。


msdn官方给出的动态添加TemplateField方法


将两种方法结合demo

前台页面一个Button一个GridView

<asp:Button ID="Button1" runat="server" Text="查询" onclick="Button1_Click" />
<div>
            <asp:GridView ID="GridView1" runat="server" DataKeyNames="RequireNo" 
                EnableViewState="False" ShowFooter="true"
            CssClass="gridview" width="99%" Font-Size="X-Small" Font-Bold="true" EmptyDataText="没有数据"  
            AutoGenerateColumns="False" RowStyle-HorizontalAlign="center" 
                OnRowDataBound="GridView1_RowDataBound">
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="25px"/>
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="#D1DDF1" />
            <RowStyle HorizontalAlign="Center" Height="25px" BackColor="#EFF3FB"/>
            <EmptyDataRowStyle ForeColor="Red" HorizontalAlign="Center" />
            <Columns>
                <asp:TemplateField HeaderText="序号">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" Font-Size="XX-Small" CommandName="Select" runat="Server"> <%# Eval("RequireNo")%> </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Require_Title" HeaderText="需求标题" ItemStyle-width="230px" HeaderStyle-Font-Size="XX-Small" ItemStyle-Font-Size="XX-Small" />                
                <asp:TemplateField HeaderText="审核">
                    <HeaderTemplate>
                        <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="chk" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                
                </Columns>                                
        </asp:GridView>
        </div>
后台,给GridView 动态绑定一个BoundField和一个TextBox(TemplateField )

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;
using DBUtility;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        RequireInfo a = new RequireInfo();
        a.Department = "IT";
        GridView1.DataSource = Require.GetRequireListByA(a);
         //动态加入列之前先将之前加入的列清除,防止重复列出现
        for (int i = 1; i <= GridView1.Columns.Count; i++)
        {
            if (i > 1 && i < GridView1.Columns.Count - 2)
            {
                GridView1.Columns.RemoveAt(i);
            }
        }
        //创建好的GridView中移除某个列:
        //GridView1.Columns.RemoveAt(1); 
        //在创建好的GridView中添加一列:
        //构造一个数据列对象出来
        BoundField column = new BoundField();
        column.HeaderText = "公司";
        //column.SortExpression = "subcompany";//指定排序的字段
        column.DataField = "subcompany";//数据字段名称(类的属性)        
        //加此数据列进入GridView
        //GridView1.Columns.Add(column);
        //----或者插入到指定位置
        GridView1.Columns.Insert(1, column);//插在第一列后(显示在第二列)
        TemplateField customField = new TemplateField();//需要引用System.Web.UI.WebControls;
        customField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "Proposer");
        customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "Proposer");
        // Add the field column to the Columns collection of the
        // GridView control.
        GridView1.Columns.Insert(2, customField);
        GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //鼠标经过时,行背景色变 
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#66CCFF'");
            //鼠标移出时,行背景色变 
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
    }
}
public class GridViewTemplate : ITemplate
{
    private DataControlRowType templateType;
    private string columnName;

    public GridViewTemplate(DataControlRowType type, string colname)
    {
        templateType = type;
        columnName = colname;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (templateType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "<b>" + columnName + "</b>";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                TextBox Name = new TextBox();
                Name.DataBinding += new EventHandler(this.Name_DataBinding);
                container.Controls.Add(Name);
                break;
            default:
                // Insert code to handle unexpected values.
                break;
        }
    }

    private void Name_DataBinding(Object sender, EventArgs e)
    {
        TextBox l = (TextBox)sender;
        GridViewRow row = (GridViewRow)l.NamingContainer;
        l.Text = DataBinder.Eval(row.DataItem, "Proposer").ToString();
    }
}



你可能感兴趣的:(GridView,asp.net,动态列)