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="http://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="http://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="http://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下载

目录
打赏
0
0
0
0
122
分享
相关文章
【YashanDB知识库】共享利用Python脚本解决Oracle的SQL脚本@@用法
【YashanDB知识库】共享利用Python脚本解决Oracle的SQL脚本@@用法
ASP.NET连接SQL数据库:详细步骤与最佳实践指南ali01n.xinmi1009fan.com
随着Web开发技术的不断进步,ASP.NET已成为一种非常流行的Web应用程序开发框架。在ASP.NET项目中,我们经常需要与数据库进行交互,特别是SQL数据库。本文将详细介绍如何在ASP.NET项目中连接SQL数据库,并提供最佳实践指南以确保开发过程的稳定性和效率。一、准备工作在开始之前,请确保您
477 3
【YashanDB知识库】共享利用Python脚本解决Oracle的SQL脚本@@用法
本文来自YashanDB官网,介绍如何处理Oracle客户端sql*plus中使用@@调用同级目录SQL脚本的场景。崖山数据库23.2.x.100已支持@@用法,但旧版本可通过Python脚本批量重写SQL文件,将@@替换为绝对路径。文章通过Oracle示例展示了具体用法,并提供Python脚本实现自动化处理,最后调整批处理脚本以适配YashanDB运行环境。
Web学习_SQL注入_联合查询注入
联合查询注入是一种强大的SQL注入攻击方式,攻击者可以通过 `UNION`语句合并多个查询的结果,从而获取敏感信息。防御SQL注入需要多层次的措施,包括使用预处理语句和参数化查询、输入验证和过滤、最小权限原则、隐藏错误信息以及使用Web应用防火墙。通过这些措施,可以有效地提高Web应用程序的安全性,防止SQL注入攻击。
152 2
SQL Server 临时存储过程及示例
SQL Server 临时存储过程及示例
99 3
ASP连接SQL数据库:从基础到实践
随着互联网技术的快速发展,数据库与应用程序之间的连接成为了软件开发中的一项关键技术。ASP(ActiveServerPages)是一种在服务器端执行的脚本环境,它能够生成动态的网页内容。而SQL数据库则是一种关系型数据库管理系统,广泛应用于各类网站和应用程序的数据存储和管理。本文将详细介绍如何使用A
155 3
|
6月前
|
SQL
Web for Pentester SQL sql注入靶场
Web for Pentester SQL sql注入靶场
mysql编写sql脚本:要求表没有主键,但是想查询没有相同值的时候才进行插入
mysql编写sql脚本:要求表没有主键,但是想查询没有相同值的时候才进行插入
68 0
VB.NET中如何利用ASP.NET进行Web开发
在VB.NET中利用ASP.NET进行Web开发是一个常见的做法,特别是在需要构建动态、交互式Web应用程序时。ASP.NET是一个由微软开发的开源Web应用程序框架,它允许开发者使用多种编程语言(包括VB.NET)来创建Web应用程序。
172 6

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等