asp.Net中Gridview动态创建模板列

转自:http://blog.csdn.net/chinajiyong/article/details/7242175

       Web中有时候数据源字段不确定,需要在绑定后添加新的字段,有没有方法了?方法是有的:之前也在网上搜索过,找到了一些方法,通过模板列可以实现。这里借鉴一下,自己亲自试验了一下,达到了想要的效果。

Gridview动态添加模板列,下面就添加一空白列作为示例。

前台代码:

[csharp] view plain copy
  1. <span style="font-size:16px;"><%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs"  
  2.     Inherits="WebApplication1.WebForm3" %>  
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>无标题页</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.     </div>  
  13.     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">  
  14.         <Columns>  
  15.             <asp:BoundField DataField="SID" HeaderText="学生ID" ReadOnly="True" />  
  16.             <asp:BoundField DataField="SName" HeaderText="姓名" />  
  17.             <asp:BoundField DataField="SAge" HeaderText="年龄" />  
  18.             <asp:BoundField DataField="SSex" HeaderText="性别" />  
  19.             <asp:BoundField DataField="SCollege" HeaderText="所属学院" />  
  20.             <asp:CommandField HeaderText="选择" ShowSelectButton="True" />  
  21.         </Columns>  
  22.     </asp:GridView>  
  23.     <br />  
  24.     <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />  
  25.     </form>  
  26. </body>  
  27. </html></span><span style="font-size: 24px;">  
  28. </span>  
后台绑定数据库数据代码如下:

[csharp] view plain copy
  1. public static string ConnectionString = @"Data Source=.;Initial Catalog=StudentMSG;Persist  Security Info=True;User ID=sa;Password=sa";  
  2.        protected void Page_Load(object sender, EventArgs e)  
  3.        {  
  4.            if (!IsPostBack)  
  5.            {  
  6.                BindData();  
  7.            }  
  8.        }  
  9.        private void BindData()  
  10.        {  
  11.            // make the query   
  12.            string query = "SELECT * FROM Stable";  
  13.            SqlConnection myConnection = new SqlConnection(ConnectionString);  
  14.            SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);  
  15.            DataSet ds = new DataSet();  
  16.            ad.Fill(ds, "Stable");  
  17.            GridView1.DataSource = ds;  
  18.            GridView1.DataKeyNames = new string[] { "SID" };//主键  
  19.            GridView1.DataBind();  
  20.        }  

显示的界面如下:

dd

那么,怎添加一列呢??动态添加列,关键是实现 ITemplate.InstantiateIn 方法。下面就自定义一个GridViewTemplate

[csharp] view plain copy
  1. public class GridViewTemplate : ITemplate  
  2.         {  
  3.             public delegate void EventHandler(object sender, EventArgs e);  
  4.             public event EventHandler eh;  
  5.             private DataControlRowType templateType;  
  6.             private string columnName;  
  7.             private string controlID;  
  8.             public GridViewTemplate(DataControlRowType type, string colname)  
  9.             {  
  10.                 templateType = type;  
  11.                 columnName = colname;  
  12.             }  
  13.             public GridViewTemplate(DataControlRowType type, string controlID, string colname)  
  14.             {  
  15.                 templateType = type;  
  16.                 this.controlID = controlID;  
  17.                 columnName = colname;  
  18.             }  
  19.             public void InstantiateIn(System.Web.UI.Control container)  
  20.             {  
  21.                 switch (templateType)  
  22.                 {  
  23.                     case DataControlRowType.Header:  
  24.                         Literal lc = new Literal();  
  25.                         lc.Text = columnName;  
  26.                         container.Controls.Add(lc);  
  27.                         break;  
  28.                     case DataControlRowType.DataRow://可以定义自己想显示的控件以及绑定事件  
  29.                         break;  
  30.                     default:  
  31.                         break;  
  32.                 }  
  33.             }  
  34.        }  
GridView模板定义好了。现在就可以添加新列,重写OnInit,代码如下:
[csharp] view plain copy
  1. protected override void OnInit(EventArgs e)  
  2.     {  
  3.         TemplateField customField = new TemplateField();  
  4.         customField.ShowHeader = true;  
  5.         customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "添加行");//添加的列标题  
  6.         GridViewTemplate gvt = new GridViewTemplate(DataControlRowType.DataRow, "");//空白列  
  7.         customField.ItemTemplate = gvt;  
  8.         GridView1.Columns.Add(customField);  
  9.         base.OnInit(e);  
  10.     }  
到此就可以显示新添加的列了。效果如下:

GG

因为之前遇到这样的问题:Gridview在绑定数据源后,发觉要添加新字段,即添加一列数据,而且要导出到Excel。按照一般的添加之后,导出Excel后发觉新添加的那列数据似乎并没有导出到Excel。如果用模板列的话,就可以解决上述的问题。

导出Excel代码如下:

[csharp] view plain copy
  1. protected void Button1_Click(object sender, EventArgs e)  
  2.     {  
  3.         if (GridView1 != null)  
  4.         {  
  5.             Response.Clear();  
  6.             Response.Buffer = true;  
  7.             Response.Charset = "GB2312";  
  8.             Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode("订卷统计") + ".xls");  
  9.             // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!  
  10.             Response.ContentEncoding = System.Text.Encoding.UTF7;  
  11.             Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。   
  12.             System.IO.StringWriter oStringWriter = new System.IO.StringWriter();  
  13.             System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);  
  14.             this.GridView1.RenderControl(oHtmlTextWriter);  
  15.             Response.Output.Write(oStringWriter.ToString());  
  16.             Response.Flush();  
  17.             Response.End();  
  18.         }  
  19.         else  
  20.         {  
  21.             this.Response.Write("<script language=javascript>alert('没有符合条件的记录!')</script>");  
  22.         }  
  23.     }  
  24.     public override void VerifyRenderingInServerForm(Control control)  
  25.     {  
  26.         // Confirms that an HtmlForm control is rendered for  
  27.     }  

如上述添加空白列后导出Excel截图如下:

tt


叙述完毕,本文参考文章:GridView动态添加模板列,里面有对事件处理。值得参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值