search
HomeWeb Front-endHTML TutorialAn example of using the server control GridView to implement data addition, deletion, modification and query in ASP.NET_html/css_WEB-ITnose

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();        }    }}
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

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

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

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.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

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

How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

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, �...

How to modify the playback control style of HTML videoHow to modify the playback control style of HTML videoApr 30, 2025 pm 03:18 PM

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.

What problems will be caused by using native select on your phone?What problems will be caused by using native select on your phone?Apr 30, 2025 pm 03:15 PM

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?What are the disadvantages of using native select on your phone?Apr 30, 2025 pm 03:12 PM

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...

How to optimize collision handling of third-person roaming in a room using Three.js and Octree?How to optimize collision handling of third-person roaming in a room using Three.js and Octree?Apr 30, 2025 pm 03:09 PM

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...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor