使用前提,知道gridview通用的扩展方法,知道反射的知识。
using System; using System.Data; using System.Configuration; 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.Collections; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; /// <summary> ///MyGridView 的摘要说明 /// </summary> public class MyGridView { GridView gv; IList list; Type t; object obj; public MyGridView( GridView gv,IList list,object obj) { this.gv = gv; this.list = list; this.obj = obj; if (list.Count > 0) { t = list[0].GetType(); } } #region BindEvents public void BindEvents() { gv.RowEditing += new GridViewEditEventHandler(gv_RowEditing); gv.RowCancelingEdit += new GridViewCancelEditEventHandler(gv_RowCancelingEdit); gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting); gv.RowUpdating += new GridViewUpdateEventHandler(gv_RowUpdating); } void gv_RowUpdating(object sender, GridViewUpdateEventArgs e) { int i = 0; PropertyInfo[] proInfo = t.GetProperties(); foreach (TableCell cell in gv.Rows[e.RowIndex].Cells) { TextBox txtBox = cell.Controls[0] as TextBox; if (txtBox != null) { proInfo[i].SetValue(list[e.RowIndex], txtBox.Text, null); } i++; } obj.GetType().GetMethod("Save").Invoke(obj, null); gv.EditIndex = -1; } void gv_RowDeleting(object sender, GridViewDeleteEventArgs e) { list.RemoveAt(e.RowIndex); } void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gv.EditIndex = -1; } void gv_RowEditing(object sender, GridViewEditEventArgs e) { gv.EditIndex = e.NewEditIndex; } #endregion public void BindData() { gv.DataSource = list; gv.DataBind(); } }
本文转自today4king博客园博客,原文链接:http://www.cnblogs.com/jinzhao/archive/2009/06/07/1497961.html
,如需转载请自行联系原作者