1、首先添加一个模板类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NSDPWeb.DbAccess.Introduction
{
//动态添加模版类
public class GridViewTemplate : ITemplate
{
public delegate void EventHandler(object sender, EventArgs e);
public event EventHandler eh;
private DataControlRowType templateType;
private string columnName;
private string controlID;
public GridViewTemplate(DataControlRowType type, string colname)
{
templateType = type;
columnName = colname;
}
public GridViewTemplate(DataControlRowType type, string controlID, string colname)
{
templateType = type;
this.controlID = controlID;
columnName = colname;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = columnName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
LinkButton lbtn = new LinkButton();
lbtn.ID = this.controlID;
if (eh != null)
{
lbtn.Click += new System.EventHandler(eh);
}
lbtn.DataBinding += new System.EventHandler(lbtn_DataBinding);
container.Controls.Add(lbtn);
break;
default:
break;
}
}
void lbtn_DataBinding(object sender, EventArgs e)
{
LinkButton lbtn = sender as LinkButton;
if (lbtn != null)
{
GridViewRow container = lbtn.NamingContainer as GridViewRow;
if (container != null)
{
object dataValue = DataBinder.Eval(container.DataItem, columnName);
if (dataValue != DBNull.Value)
{
lbtn.Text = dataValue.ToString();
}
}
}
}
}
}
2、前台
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
3、后台
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NSDPWeb.DbAccess.Introduction;
using DataAccess;
namespace NSDPWeb.Pages.Introduction
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table =BaseDb.RunProcedureForQuery("IntroSelectAll", null).Tables[0];
GridView1.DataSource = table;
GridView1.DataBind();
}
protected override void OnInit(EventArgs e)
{
TemplateField customField = new TemplateField();
customField.ShowHeader = true;
customField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, "动态添加列");
GridViewTemplate gvt = new GridViewTemplate(DataControlRowType.DataRow, "lbtn", "姓名");
gvt.eh += new GridViewTemplate.EventHandler(lbtn_Click);
customField.ItemTemplate = gvt;
GridView1.Columns.Add(customField);
base.OnInit(e);
}
public void lbtn_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "test", "alert('ok');", true);
//Response.Redirect(String.Format("~/Pages/Introduction/IntroStudentDetail.aspx?numberid={0}&category={1}", Eval("编号"), Eval("类别")));
}
}
}