ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能

简介: ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能

ASP.NET Web——GridView

完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能


环境说明

系统要求:win7/10/11

开发语言:C#

开发工具:Visual Studio 2012/2017/2019/2022,本示例使用的是Visual Studio 2017

项目创建:ASP.NET Web应用程序(.NET Framework)

数据库:SQLServer 2012/2014/2017/2019,本示例使用的是SQLServer 2014

数据库工具:Navicat

功能演示

ASP.NET Web增删改查演示(ASP.NET Web——GridView完整增删改查示例(全篇幅包含sql脚本)大二结业考试必备技能)

数据库脚本

建表语句

CREATE TABLE [dbo].[users] (
[id] varchar(32) COLLATE Chinese_PRC_CI_AS NOT NULL DEFAULT (replace(newid(),'-','')) ,
[createDate] datetime NOT NULL DEFAULT (getdate()) ,
[userName] varchar(20) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[age] int NOT NULL ,
[introduce] varchar(200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
CONSTRAINT [PK__users__3213E83F0E2177B8] PRIMARY KEY ([id])
)
ON [PRIMARY]
GO

信息插入

INSERT INTO [dbo].[users] ([id], [createDate], [userName], [age], [introduce]) VALUES (N'1a19c0945dfc44e98a715ffccdb1cc54', N'2223-08-08 18:18:22.000', N'superGirl777', N'17', N'超级女孩');
GO
INSERT INTO [dbo].[users] ([id], [createDate], [userName], [age], [introduce]) VALUES (N'1EBB75FB1DD64B678413894A4B736484', N'2222-08-08 18:18:22.000', N'貂蝉', N'16', N'吕布爱妻');
GO
INSERT INTO [dbo].[users] ([id], [createDate], [userName], [age], [introduce]) VALUES (N'7979e6d162c44ccbaf47fd3b0172ecf3', N'2222-01-01 01:01:01.000', N'周瑜', N'32', N'大都督');
GO
INSERT INTO [dbo].[users] ([id], [createDate], [userName], [age], [introduce]) VALUES (N'9BFE04E8999F415D9224CCFCEEF40927', N'2222-08-08 18:18:22.000', N'赵子龙', N'27', N'子龙浑身都是胆');
GO

创建ASP.NET Web项目

选择左侧菜单栏中的【Web】项目,右侧会弹出对应的ASP.NET Web应用程序(.NET Framework)

选择创建【Web窗体】

创建三层关系

创建类库并完成三层关系

三层关系

引入方式

注意层级引入顺序

完成DAL层DBHelper

注意换成自己的数据库连接

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace DAL
{
    public class DBHelper
    {
        //数据库连接地址
        private static string url = "Data Source=.;Initial Catalog=test;Integrated Security=True";
        public static DataTable Query(string sql)
        {
            SqlConnection conn = new SqlConnection(url);//创建链接
            SqlDataAdapter sdap = new SqlDataAdapter(sql,conn);//闭合式查询
            DataSet ds = new DataSet();//结果集
            sdap.Fill(ds);//将闭合式查询的结果放置到结果集中
            return ds.Tables[0];//返回结果集中的第一项
        }
        public static bool NoQuery(string sql) {
            SqlConnection conn = new SqlConnection(url);//创建链接
            conn.Open();//打开数据库连接
            SqlCommand cmd = new SqlCommand(sql,conn);//声明操作
            int rows=cmd.ExecuteNonQuery();//执行操作
            conn.Close();//关闭数据库连接
            return rows > 0;//判断是否操作成功
        }
    }
}

完成DAL层UsersDAL.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
    public class UsersDAL
    {
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public static DataTable GetAll() {
            string sql = "select * from users";
            return DBHelper.Query(sql);
        }
        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static DataTable GetSelectByName(string userName)
        {
            string sql = "select * from users where userName like '%" + userName + "%'";
            return DBHelper.Query(sql);
        }
        /// <summary>
        /// 添加操作DAL
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="age"></param>
        /// <param name="introduce"></param>
        /// <returns></returns>
        public static bool AddInfo(string userName, int age, string introduce) {
            string id = Guid.NewGuid().ToString("N");
            string createDate = "2023-1-4 15:24:15";
            string sql = string.Format("insert into users values('{0}','{1}','{2}',{3},'{4}')",
                id, createDate, userName, age, introduce);
            return DBHelper.NoQuery(sql);
        }
        /// <summary>
        /// 删除语句
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteById(string id) {
            string sql = "delete from users where id='" + id + "'";
            return DBHelper.NoQuery(sql);
        }
        /// <summary>
        /// 根据id进行精准查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DataTable GetSelectById(string id)
        {
            string sql = "select * from users where id='"+id+"'";
            return DBHelper.Query(sql);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="age"></param>
        /// <param name="introduce"></param>
        /// <returns></returns>
        public static bool UpdateById(string id,string age,string introduce) {
            string sql = string.Format("update users set age={0},introduce='{1}' where id='{2}'",
                age,introduce,id);
            return DBHelper.NoQuery(sql);
        }
    }
}

完成BLL层UsersBLL.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
    public class UsersBLL
    {
        public static DataTable GetAll()
        {
            return DAL.UsersDAL.GetAll();
        }
        public static DataTable GetSelectByName(string userName)
        {
            return DAL.UsersDAL.GetSelectByName(userName);
        }
        public static bool AddInfo(string userName, int age, string introduce)
        {
            return DAL.UsersDAL.AddInfo(userName, age, introduce);
        }
        public static bool DeleteById(string id)
        {
            return DAL.UsersDAL.DeleteById(id);
        }
        public static DataTable GetSelectById(string id)
        {
            return DAL.UsersDAL.GetSelectById(id);
        }
        public static bool UpdateById(string id, string age, string introduce)
        {
            return DAL.UsersDAL.UpdateById(id,age,introduce);
        }
    }
}

完成视图层Index.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Demo8.Index" %>
<!DOCTYPE html>
<html xmlns="//www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>
                <asp:TextBox runat="server" ID="selectKey"></asp:TextBox>
                <asp:Button runat="server" Text="查询" OnClick="Unnamed_Click"/>
            </p>
            <a href="AddInfo.aspx" class="btn btn-primary">添加数据</a>
            <asp:GridView CssClass="table table-bordered table-hover" runat="server" ID="showList" AutoGenerateColumns="false" OnRowCommand="showList_RowCommand">
                <Columns>
                    <asp:BoundField DataField="id" HeaderText="编号"/>
                    <asp:BoundField DataField="createDate" HeaderText="创建时间"/>
                    <asp:BoundField DataField="userName" HeaderText="昵称"/>
                    <asp:BoundField DataField="age" HeaderText="年龄"/>
                    <asp:BoundField DataField="introduce" HeaderText="简介"/>
                    <asp:TemplateField>
                        <ItemTemplate>
<asp:LinkButton runat="server" CommandName="UpdateById" CommandArgument='<%# Eval("id") %>'
    CssClass="btn btn-primary">修改</asp:LinkButton>
<asp:LinkButton runat="server" CommandName="DeleteById" CommandArgument='<%# Eval("id") %>'
    OnClientClick="return confirm('是否删除此行?')" CssClass="btn btn-primary">删除</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

完成后台Index.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo8
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //绑定数据
                this.showList.DataSource = BLL.UsersBLL.GetAll();
                //显示数据
                this.showList.DataBind();
            }
        }
        protected void Unnamed_Click(object sender, EventArgs e)
        {
            string selectKey = this.selectKey.Text;
            this.showList.DataSource = BLL.UsersBLL.GetSelectByName(selectKey);
            //显示数据
            this.showList.DataBind();
        }
        protected void showList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteById")
            {
                BLL.UsersBLL.DeleteById(e.CommandArgument.ToString());
                Response.Redirect("Index.aspx");
            } else if (e.CommandName == "UpdateById") {
                Response.Redirect("UpdateById.aspx?id="+e.CommandArgument.ToString());
            }
        }
    }
}

完成视图层AddInfo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddInfo.aspx.cs" Inherits="Demo8.AddInfo" %>
<!DOCTYPE html>
<html xmlns="//www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>
                <asp:TextBox runat="server" ID="userName" placeholder="请输入昵称"></asp:TextBox>
            </p>
            <p>
                <asp:TextBox runat="server" ID="age" placeholder="请输入年龄"></asp:TextBox>
            </p>
            <p>
                <asp:TextBox runat="server" ID="introduce" placeholder="请输入简介"></asp:TextBox>
            </p>
            <p>
                <asp:Button runat="server" Text="添加" OnClick="Unnamed_Click"/>
            </p>
        </div>
    </form>
</body>
</html>

完成后台AddInfo.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo8
{
    public partial class AddInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Unnamed_Click(object sender, EventArgs e)
        {
            string userName=this.userName.Text;
            int age=int.Parse(this.age.Text);
            string introduce = this.introduce.Text;
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(this.age.Text)
                || string.IsNullOrEmpty(introduce)) {
                Response.Write("<script>alert('参数不允许有空存在!');</script>");
                return;
            }
            bool isf=BLL.UsersBLL.AddInfo(userName,age,introduce);
            if (isf)
            {
                Response.Redirect("Index.aspx");
            }
            else {
                Response.Write("<script>alert('添加失败!');</script>");
            }
        }
    }
}

完成视图层UpdateById.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpdateById.aspx.cs" Inherits="Demo8.UpdateById" %>
<!DOCTYPE html>
<html xmlns="//www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>
                <asp:TextBox runat="server" ID="id" ReadOnly="true"></asp:TextBox>
            </p>
            <p>
                <asp:TextBox runat="server" ID="age"></asp:TextBox>
            </p>
            <p>
                <asp:TextBox runat="server" ID="introduce"></asp:TextBox>
            </p>
            <p>
                <asp:Button runat="server" Text="提交修改" OnClick="Unnamed_Click"/>
            </p>
        </div>
    </form>
</body>
</html>

完成后台UpdateById.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo8
{
    public partial class UpdateById : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                string id = Request.QueryString["id"];
                DataTable dt = BLL.UsersBLL.GetSelectById(id);
                this.id.Text = dt.Rows[0]["id"].ToString();
                this.age.Text = dt.Rows[0]["age"].ToString();
                this.introduce.Text = dt.Rows[0]["introduce"].ToString();
            }
        }
        protected void Unnamed_Click(object sender, EventArgs e)
        {
            string id=this.id.Text;
            string age = this.age.Text;
            string introduce = this.introduce.Text;
            if (
                string.IsNullOrEmpty(id)||
                string.IsNullOrEmpty(age)||
                string.IsNullOrEmpty(introduce)
                ) {
                Response.Write("<script>alert('参数不允许为空!');<script>");
                return;
            }
            BLL.UsersBLL.UpdateById(id,age,introduce);
            Response.Redirect("Index.aspx");
        }
    }
}

最终执行效果:

项目源码地址:

ASP.NETWeb-GridView完整增删改查示例项目源码-大二结业考试必备技能-C#文档类资源-CSDN下载

相关文章
|
4月前
|
SQL 存储 数据处理
探索SQL技能提升的七个高阶使用技巧。
通过上述技巧的运用,可以使得数据库查询更为高效、安全而且易于维护。这些技巧的掌握需要在实际应用中不断地实践和反思,以不断提高数据处理的速度和安全性。
137 25
|
11月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
692 3
|
SQL 开发框架 .NET
ASP.NET连接SQL数据库:详细步骤与最佳实践指南ali01n.xinmi1009fan.com
随着Web开发技术的不断进步,ASP.NET已成为一种非常流行的Web应用程序开发框架。在ASP.NET项目中,我们经常需要与数据库进行交互,特别是SQL数据库。本文将详细介绍如何在ASP.NET项目中连接SQL数据库,并提供最佳实践指南以确保开发过程的稳定性和效率。一、准备工作在开始之前,请确保您
739 3
|
11月前
|
SQL 存储 数据挖掘
使用Python和PDFPlumber进行简历筛选:以SQL技能为例
本文介绍了一种使用Python和`pdfplumber`库自动筛选简历的方法,特别是针对包含“SQL”技能的简历。通过环境准备、代码解析等步骤,实现从指定文件夹中筛选出含有“SQL”关键词的简历,并将其移动到新的文件夹中,提高招聘效率。
266 8
使用Python和PDFPlumber进行简历筛选:以SQL技能为例
|
11月前
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
开发框架 前端开发 .NET
VB.NET中如何利用ASP.NET进行Web开发
在VB.NET中利用ASP.NET进行Web开发是一个常见的做法,特别是在需要构建动态、交互式Web应用程序时。ASP.NET是一个由微软开发的开源Web应用程序框架,它允许开发者使用多种编程语言(包括VB.NET)来创建Web应用程序。
292 7
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
199 3
|
开发框架 .NET 中间件
ASP.NET Core Web 开发浅谈
本文介绍ASP.NET Core,一个轻量级、开源的跨平台框架,专为构建高性能Web应用设计。通过简单步骤,你将学会创建首个Web应用。文章还深入探讨了路由配置、依赖注入及安全性配置等常见问题,并提供了实用示例代码以助于理解与避免错误,帮助开发者更好地掌握ASP.NET Core的核心概念。
275 3
|
开发框架 前端开发 JavaScript
二级Web计算机等级考试例题
提供全国计算机二级考试的练习题库,涵盖Web浏览器和服务器间传输协议、HTTP特点、DOM、JavaScript客户端执行、HTTP/1.1持久连接、表格标记、ASP.NET描述、四舍五入函数、Internet服务等题目,并给出答案。