


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(); } }}

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

What are the disadvantages of using native select on your phone? When developing applications on mobile devices, it is very important to choose the right UI components. Many developers...

Use Three.js and Octree to optimize collision handling of third-person roaming in the room. Use Octree in Three.js to implement third-person roaming in the room and add collisions...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor
