Note: This is an example from a project development team I coached. I will share it in the form of an article for reference by more friends. In fact, in our projects in the past few years, we have rarely used server controls, but more often adopted the MVC development model. However, if the historical background of the project uses server controls, you may as well continue to use them to avoid too much change, which will be detrimental to the overall development of the project.
The pages of many enterprise business programs are actually operations on data, such as adding, deleting, modifying and querying (referred to as: adding, deleting, modifying and querying). If it is possible to completely implement it in one page ( No need to go around several pages), which may provide a better experience for users.
ASP.NET began to provide a variety of data controls in 2.0, and adopted a template mechanism to make our above needs possible. What I’m going to talk about today is the use of GridView, which is known as the most complex control in ASP.NET. It can fully realize addition, deletion, modification and query.
Page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationSample.Default" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:GridView ID="gvData" runat="server" OnRowDeleting="gvData_RowDeleting" OnRowUpdating="gvData_RowUpdating" OnRowCancelingEdit="gvData_RowCancelingEdit" OnRowEditing="gvData_RowEditing" AutoGenerateColumns="true" AutoGenerateDeleteButton="true" AutoGenerateEditButton="true"> <%--<Columns> <asp:CommandField HeaderText="操作" UpdateText="保存" CancelText="取消" DeleteText="删除" ShowDeleteButton="true" ShowEditButton="true" EditText="编辑" /> </Columns>--%> </asp:GridView> <asp:Button ID="btAddNew" runat="server" Text="添加新记录" OnClick="btAddNew_Click" /> </div> </form> <script> //这里为所有删除按钮都处理一个事件,请用户确认 var links = document.links;//获取所有的链接 for (var i in links) {//循环他们 var a = links[i];//取得当前这个链接 if (a.text == "Delete" || a.text=="删除") {//如果是删除按钮的话 var o = a.href;//获取这个链接的地址(默认会生成一个执行javascript的地址的) a.href = "#";//将这个地址删除掉,就是不要让他执行默认的行为 a.addEventListener("click", function () {//添加一个新的事件注册 var result = window.confirm("你是否真的要删除?");//向用户确认是否要删除 if (result == true)//如果用户确定 eval(o);//执行原先默认的那个方法(去服务器删除数据) return false; }); } } </script></body></html>
Code:
using System;using System.Collections.Generic;using System.Web.UI.WebControls;namespace WebApplicationSample{ /// <summary> /// 这个实例主要演示了如何使用GridView进行数据的增、删、改、查。 /// 更多有关于该控件的知识,可以参考 http://msdn.microsoft.com/zh-cn/library/vstudio/system.web.ui.webcontrols.gridview.aspx (请仔细阅读) /// </summary> public partial class Default : System.Web.UI.Page { /// <summary> /// 这是我们定义的一个业务实体类,用来保存界面上的列表数据,为了保存,必须支持序列化 /// </summary> [Serializable] public class Employee { public string FirstName { get; set; } public string LastName { get; set; } } private List<Employee> data = new List<Employee>();//这是用来保存那个列表数据的字段 /// <summary> /// 重写这个方法来保存视图状态。因为每次页面刷新的时候,默认情况下,data都会被清空,如果希望在多次回发的过程中保存数据,则重写该方法 /// </summary> /// <returns></returns> protected override object SaveViewState() { var obj = new object[] { base.SaveViewState(), data }; return obj; } /// <summary> /// 重写该方法,是与上面这个方法配套,在回发回来之后加载并还原 /// </summary> /// <param name="savedState"></param> protected override void LoadViewState(object savedState) { var obj = savedState as object[]; base.LoadViewState(obj[0]); data = obj[1] as List<Employee>; } /// <summary> /// 页面初始化的时候执行该代码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) {//这里只是一个示例,默认给页面添加一个初始的员工,实际在做的时候,可以不加 data = new List<Employee>(){ new Employee(){FirstName ="ares",LastName ="chen"} }; gvData.DataSource = data; gvData.DataBind(); } } /// <summary> /// 添加新的员工时执行该代码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btAddNew_Click(object sender, EventArgs e) { data.Add(new Employee());//创建一个空的对象 gvData.DataSource = data;//设置数据源 gvData.EditIndex = data.Count - 1;//设置当前这个对象为编辑状态 gvData.DataBind();//绑定数据 } /// <summary> /// 当用户决定要删除某一行数据时执行该代码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e) { //删除某一行 data.RemoveAt(e.RowIndex); gvData.DataSource = data; gvData.EditIndex = -1; gvData.DataBind(); } /// <summary> /// 当用户要保存修改时执行该代码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e) { var index = e.RowIndex;//获取当前编辑行当索引号 var row = gvData.Rows[index];//获取当前用户编辑的这一行 var firstName = (row.Cells[1].Controls[0] as TextBox).Text;//获取用户输入的数据 var lastName = (row.Cells[2].Controls[0] as TextBox).Text;//获取用户输入的数据 var emp = data[index];//找到这个对象 emp.FirstName = firstName; emp.LastName = lastName; gvData.DataSource = data; gvData.EditIndex = -1;//退出编辑状态 gvData.DataBind(); } /// <summary> /// 当用户要取消编辑的时候 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gvData.DataSource = data; gvData.EditIndex = -1; gvData.DataBind(); } /// <summary> /// 当用户要进行编辑的时候 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvData_RowEditing(object sender, GridViewEditEventArgs e) { gvData.DataSource = data; gvData.EditIndex = e.NewEditIndex; gvData.DataBind(); } }}