全部由后台cs代码实现GirdView的各种功能,实现了GridView的所有事件:
1.GridView动态创建控件,而且回发不会消失,绑定事件依然有效。
2.分页,动态添加页脚页码控件,且绑定事件
3.在最合适的地方动态注册添加js事件
4.实现删除、编辑、插入、查找、更新"、取消、新建、选择等事件
5.动态创建模板列,含编辑模板列
6.自定义点击表头排序
7.最合适的地方动态添加css样式
<asp:GridView ID="GridView1" runat="server" OnRowUpdating="GridView1_RowUpdating" onrowcancelingedit="GridView1_RowCancelingEdit" onrowediting="GridView1_RowEditing" onsorting="GridView1_Sorting" AllowSorting="True" ondatabound="GridView1_DataBound" onrowdatabound="GridView1_RowDataBound" onsorted="GridView1_Sorted" AutoGenerateColumns="false" ondatabinding="GridView1_DataBinding" oninit="GridView1_Init" onload="GridView1_Load" onrowupdated="GridView1_RowUpdated" ondisposed="GridView1_Disposed" onpageindexchanged="GridView1_PageIndexChanged" onpageindexchanging="GridView1_PageIndexChanging" onprerender="GridView1_PreRender" onrowcommand="GridView1_RowCommand" onrowcreated="GridView1_RowCreated" onrowdeleted="GridView1_RowDeleted" onrowdeleting="GridView1_RowDeleting" onselectedindexchanged="GridView1_SelectedIndexChanged" onselectedindexchanging="GridView1_SelectedIndexChanging" onunload="GridView1_Unload" AllowPaging="True" PageSize="3" > </asp:GridView>
cs文件代码
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Reflection; namespace a.b.c { public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void GridView1_Init(object sender, EventArgs e) { DataTable dt = new DataTable("ttt"); dt.Columns.Add("c1"); dt.Columns.Add("c2", typeof(int)); dt.Columns.Add("c3"); dt.Rows.Add("1", 11, "r1811"); dt.Rows.Add("2", 21, "rkey2"); dt.Rows.Add("3", 1131, "r1113"); dt.Rows.Add("4", 41, "r1181"); dt.Rows.Add("5", 51, "rkey22"); dt.Rows.Add("6", 613, "r11413"); dt.Rows.Add("7", 71, "r1115"); ViewState["dt"] = dt; GridView gv = (GridView)sender; int index = -1; foreach (DataColumn dc in dt.Columns) { BoundField bf = new BoundField(); bf.HeaderText = dc.ColumnName; bf.DataField = dc.ColumnName; bf.SortExpression = dc.ColumnName; gv.Columns.Insert(++index, bf); } TemplateField tf = new TemplateField(); tf.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "编辑", false) { eddhander=new EventHandler(btn_Click)}; tf.EditItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "更新", true); gv.Columns.Add(tf); CommandField cd = new CommandField(); cd.HeaderText = "综合操作"; cd.InsertText = "插入"; cd.DeleteText = "删除"; cd.EditText = "编辑"; cd.SelectText = "查找"; cd.UpdateText = "更新"; cd.CancelText = "取消"; cd.NewText = "新建"; cd.SelectText = "选择"; cd.ButtonType = ButtonType.Button; cd.ShowInsertButton = cd.ShowDeleteButton = cd.ShowEditButton = cd.ShowSelectButton = cd.ShowCancelButton = cd.ShowSelectButton = true; gv.Columns.Add(cd); } void btn_Click(object sender, EventArgs e)//自定义按钮事件 { Response.Write(DateTime.Now.ToString()); } protected void GridView1_Load(object sender, EventArgs e) { GridView gv = (GridView)sender; if (!IsPostBack) { gv.DataBind(); } } protected void GridView1_DataBinding(object sender, EventArgs e) { GridView gv = (GridView)sender; DataTable dt = ViewState["dt"] as DataTable; DataCount = dt.Rows.Count; DataView dv = new DataView(dt); if (ViewState["sortstr"] != null && ViewState["sortstr"].ToString().Length > 0) dv.Sort = ViewState["sortstr"].ToString(); gv.DataKeyNames = new[] { "c1" }; gv.DataSource = dv; } protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='teal'"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''"); foreach (DataControlFieldCell fc in e.Row.Cells) foreach (Control c in fc.Controls) if (c is Button && (c as Button).CommandName == "Delete") (c as Button).Attributes.Add("onclick", "if(!confirm('您确定删除该项吗?')) return;"); } else if (e.Row.RowType == DataControlRowType.Footer) { GridView gv = (GridView)sender; DropDownList dp = new DropDownList(); for (int i = 0; i < gv.PageCount; i++) dp.Items.Add(new ListItem((i + 1).ToString(), i.ToString())); dp.AutoPostBack = true; dp.SelectedIndexChanged += new EventHandler(dp_SelectedIndexChanged); dp.SelectedValue = gv.PageIndex.ToString(); e.Row.Cells[0].Controls.Add(dp); } //引发GridView1_RowDataBound } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { //下面的代码可以写在GridView1_RowCreated中 //e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='red'"); //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''"); foreach (TableCell tc in e.Row.Cells) if (tc.Text.Contains("key")) tc.Text = tc.Text.Replace("key", "<font color=red>key</font>"); //tc.Attributes.Add("style","color:red"); } } protected void GridView1_DataBound(object sender, EventArgs e) { //在绑定完所有数据后触发 GridView gv = (GridView)sender; int count = gv.Rows.Count; if (count > 0 && count % gv.PageSize > 0) for (int i = 0; i < gv.PageSize - count % gv.PageSize; i++) { //dt.Rows.Add(dt.NewRow()); GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal); for (int j = 0; j < gv.Rows[0].Cells.Count; j++) { TableCell cell = new TableCell(); cell.Text = " "; row.Cells.Add(cell); } gv.FooterRow.Controls[0].Controls.Add(row); } } protected void GridView1_PreRender(object sender, EventArgs e) { GridView gv = (GridView)sender; gv.Attributes.Add("style", "border:solid 2px yellow"); //可以注册js到客户端 //客户端脚本,响应网页的onunload事件 //this.ClientScript.RegisterClientScriptBlock(this.GetType(), "unload", "<SCRIPT event='onunload' for='window'>alert('页面卸载');</SCRIPT>"); } protected void GridView1_Unload(object sender, EventArgs e) { ViewState.Remove("dt"); } protected void GridView1_Disposed(object sender, EventArgs e) { //XXXXX.Dispose(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView gv = (GridView)sender; gv.AllowSorting = false; gv.EditIndex = e.NewEditIndex; gv.DataBind(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { DataTable dt = ViewState["dt"] as DataTable; dt.Rows[e.RowIndex]["c1"] = (GridView1.Rows[e.RowIndex].Cells[0].Controls[0] as TextBox).Text; dt.Rows[e.RowIndex]["c2"] = (GridView1.Rows[e.RowIndex].Cells[1].Controls[0] as TextBox).Text; dt.Rows[e.RowIndex]["c3"] = (GridView1.Rows[e.RowIndex].Cells[2].Controls[0] as TextBox).Text; ViewState["dt"] = dt; GridView gv = (GridView)sender; gv.AllowSorting = true; gv.EditIndex = -1; gv.DataBind(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView gv = (GridView)sender; gv.AllowSorting = true; gv.EditIndex = -1; gv.DataBind(); } protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e) { //e.KeepInEditMode = false; //在没有绑定DataSourceID的情况下,暂时确定为不会触发 } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { DataTable dt = ViewState["dt"] as DataTable; dt.Rows[e.RowIndex].Delete(); ViewState["dt"] = dt; GridView gv = (GridView)sender; gv.DataBind(); } protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e) { //在没有绑定DataSourceID的情况下,暂时确定为不会触发 } protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { GridView gv = (GridView)sender; gv.SelectedIndex = e.NewSelectedIndex; } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView gv = (GridView)sender; gv.PageIndex = e.NewPageIndex; } protected void GridView1_PageIndexChanged(object sender, EventArgs e) { //分页事件,绑定数据 GridView gv = (GridView)sender; gv.DataBind(); } protected void dp_SelectedIndexChanged(object sender, EventArgs e) { DropDownList dp = (DropDownList)sender; GridView1.PageIndex = int.Parse(dp.SelectedValue); //GridView1.EditIndex = -1; GridView1.DataBind(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridView gv = (GridView)sender; foreach (GridViewRow r in gv.Rows) r.Font.Size = r.RowIndex == gv.SelectedIndex ? new FontUnit(16) : new FontUnit(12); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { GridView gv = (GridView)sender;//或者 GridView gv = (GridView)e.CommandSource; } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { //Type t = sender.GetType(); //BindingFlags flag = BindingFlags.NonPublic | BindingFlags.Instance; //t.GetProperty("SortExpressionInternal", flag).SetValue(sender, e.SortExpression, null); //t.GetProperty("SortDirectionInternal", flag).SetValue(sender, e.SortDirection, null); SortOrder = SortOrder == "asc" ? "desc" : "asc"; SortColumn = e.SortExpression; ViewState["sortstr"] = SortColumn + " " + SortOrder; GridView gv = (GridView)sender; gv.DataBind(); } protected void GridView1_Sorted(object sender, EventArgs e) { GridView gv = (GridView)sender; for (int i = 0; i < gv.Columns.Count; i++) if (gv.Columns[i].SortExpression == SortColumn) gv.HeaderRow.Cells[i].Controls.Add(new Literal() { Text = SortOrder == "asc" ? "↑" : "↓" }); } int DataCount { get { var obj = ViewState["DataCount"]; if (obj != null) return (int)obj; return 0; } set { ViewState["DataCount"] = value; } } string SortOrder { get { var obj = ViewState["SortOrder"]; if (obj != null) return (string)obj; return "asc"; } set { ViewState["SortOrder"] = value; } } string SortColumn { get { var obj = ViewState["SortColumn"]; if (obj != null) return (string)obj; return string.Empty; } set { ViewState["SortColumn"] = value; } } protected void Button1_Click(object sender, EventArgs e) { } protected void LinkButton1_Click(object sender, EventArgs e) { Response.Write(DateTime.Now.ToString()); } } public class GridViewTemplate : ITemplate { private DataControlRowType templateType; private string columnName; bool IsEditTemplate; public EventHandler eddhander; public GridViewTemplate(DataControlRowType type, string colname, bool _IsEditTemplate) { templateType = type; columnName = colname; IsEditTemplate = _IsEditTemplate; } 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: if (IsEditTemplate) { Button btn1 = new Button(); btn1.CausesValidation = true; btn1.CommandName = "Update"; btn1.Text = "更新"; Button btn2 = new Button(); btn2.CausesValidation = false; btn2.CommandName = "Cancel"; btn2.Text = "取消"; container.Controls.Add(btn1); container.Controls.Add(btn2); } else { Button btn3 = new Button(); btn3.CausesValidation = false; btn3.CommandName = "Edit"; btn3.Text = "编辑"; Button mmm = new Button(); mmm.Click += eddhander;//添加事件 mmm.Text = "我自定义的按钮,可输出时间"; container.Controls.Add(mmm); container.Controls.Add(btn3); } break; default: break; } } } }