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'超级女孩');GOINSERT INTO [dbo].[users] ([id], [createDate], [userName], [age], [introduce]) VALUES (N'1EBB75FB1DD64B678413894A4B736484', N'2222-08-08 18:18:22.000', N'貂蝉', N'16', N'吕布爱妻');GOINSERT INTO [dbo].[users] ([id], [createDate], [userName], [age], [introduce]) VALUES (N'7979e6d162c44ccbaf47fd3b0172ecf3', N'2222-01-01 01:01:01.000', N'周瑜', N'32', N'大都督');GOINSERT 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    {        ///         /// 查询所有        ///         ///         public static DataTable GetAll() {            string sql = "select * from users";            return DBHelper.Query(sql);        }        ///         /// 模糊查询        ///         ///         ///         public static DataTable GetSelectByName(string userName)        {            string sql = "select * from users where userName like '%" + userName + "%'";            return DBHelper.Query(sql);        }        ///         /// 添加操作DAL        ///         ///         ///         ///         ///         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);        }        ///         /// 删除语句        ///         ///         ///         public static bool DeleteById(string id) {            string sql = "delete from users where id='" + id + "'";            return DBHelper.NoQuery(sql);        }        ///         /// 根据id进行精准查询        ///         ///         ///         public static DataTable GetSelectById(string id)        {            string sql = "select * from users where id='"+id+"'";            return DBHelper.Query(sql);        }        ///         /// 修改        ///         ///         ///         ///         ///         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

                                

添加数据 ' CssClass="btn btn-primary">修改' OnClientClick="return confirm('是否删除此行" />删除

完成后台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

                                

完成后台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("alert('参数不允许有空存在!');");                return;            }            bool isf=BLL.UsersBLL.AddInfo(userName,age,introduce);            if (isf)            {                Response.Redirect("Index.aspx");            }            else {                Response.Write("alert('添加失败!');");            }        }    }}

完成视图层UpdateById.aspx

                                

完成后台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("alert('参数不允许为空!');");                return;            }            BLL.UsersBLL.UpdateById(id,age,introduce);            Response.Redirect("Index.aspx");        }    }}

最终执行效果:

项目源码地址:

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