博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET 中 对GridView(网格视图)的查、分页、编辑更新、删除操作
阅读量:5139 次
发布时间:2019-06-13

本文共 12913 字,大约阅读时间需要 43 分钟。

ylbtech-ASP.NET-Control-Bind: 对GridView(网格视图)的查、分页、编辑更新、删除操作

 ASP.NET 中 对GridView(网格视图)的查、分页、编辑更新、删除操作。

1.A,运行效果图
 
1.B,源代码
/App_Data/sql-basic.sql
View Code
use mastergoif exists(select * from sysdatabases where name='db1')begin    drop database db1endgocreate database db1gouse db1go-- ================================-- ylb:1,类别表-- ================================create table category(    categoryid int identity(1,1) primary key,    --编号【PK】    categoryname varchar(20) not null            --名称)insert into category(categoryname) values('饮料')insert into category(categoryname) values('主食')insert into category(categoryname) values('副食')insert into category(categoryname) values('蔬菜')-- ================================-- ylb:2,产品表-- ================================create table product(    productid int identity(1001,1) primary key,    --编号【PK】    productname varchar(20),        --名称    unitprice numeric(7,2),            --单价    special varchar(10) check(special in('特价','非特价')),    --是否特价【C】    categoryid int foreign key references category(categoryid)    --类别编号【FK】)insert into product(productname,unitprice,special,categoryid) values('可乐1',12.6,'特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐2',12.6,'非特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐3',12.6,'非特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐4',12.6,'非特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐5',12.6,'特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐6',12.6,'特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐7',12.6,'特价',1)insert into product(productname,unitprice,special,categoryid) values('可乐8',12.6,'特价',1)insert into product(productname,unitprice,special,categoryid) values('馒头1',12.6,'特价',2)insert into product(productname,unitprice,special,categoryid) values('豆腐1',12.6,'特价',3)insert into product(productname,unitprice,special,categoryid) values('冬瓜1',12.6,'特价',4)select * from categoryselect productid,productname,unitprice,special,categoryid from product
,2
/App_Code/
/App_Code/DBConnection.cs
View Code
using System.Data.SqlClient;/// ///DBConnection 的摘要说明///数据连接类/// public class DBConnection{    SqlConnection con = null;    public DBConnection()    {        //创建连接对象        con = new SqlConnection("Server=.;Database=db1;Uid=sa;pwd=sa");    }    ///     /// 数据连接对象    ///     public SqlConnection Con    {        get { return con; }        set { con = value; }    }}
/App_Code/CategoryInfo.cs
/App_Code/CategoryOper.cs
/App_Code/ProductInfo.cs
View Code
using System;/// ///ProductInfo 的摘要说明///产品实体类/// public class ProductInfo{    //1,Attributes    int productId;    string productName;    decimal unitprice;    string special;    int categoryId;    public ProductInfo()    {        //        //TODO: 在此处添加构造函数逻辑        //    }    //3,    ///     /// 产品编号【PK】    ///     public int ProductId    {        get { return productId; }        set { productId = value; }    }    ///     /// 产品名称    ///     public string ProductName    {        get { return productName; }        set { productName = value; }    }    ///     /// 单位价格    ///     public decimal Unitprice    {        get { return unitprice; }        set { unitprice = value; }    }    ///     /// 是否为特价【C】(特价、非特价)    ///     public string Special    {        get { return special; }        set { special = value; }    }    ///     /// 类编编号【FK】    ///     public int CategoryId    {        get { return categoryId; }        set { categoryId = value; }    }}
/App_Code/ProductOper.cs
View Code
using System;using System.Collections.Generic;using System.Data.SqlClient;/// ///ProductOper 的摘要说明/// public class ProductOper{    ///     /// 1,GetAll    ///     /// 
public static IList
GetAll() { IList
dals = new List
(); string sql = "select productId,productName,unitprice,special,categoryId from Product order by productId desc"; //1,创建连接对象 SqlConnection con = new DBConnection().Con; //2,创建命令对象 SqlCommand cmd = con.CreateCommand(); //3,把sql语句付给命令对象 cmd.CommandText = sql; //4,打开数据连接 con.Open(); try { using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { ProductInfo dal = new ProductInfo() { ProductId = sdr.GetInt32(0), ProductName = sdr.GetString(1), Unitprice = sdr.GetDecimal(2), Special = sdr.GetString(3), CategoryId = sdr.GetInt32(4) }; dals.Add(dal); } } } finally { //,关闭数据连接(释放资源) con.Close(); } return dals; } public static void Add(ProductInfo dal) { string sql = "insert into Product(productName,unitprice,special,categoryId) values(@productName,@unitprice,@special,@categoryId)"; SqlConnection con = new DBConnection().Con; SqlCommand cmd = con.CreateCommand(); cmd.CommandText = sql; //配参数 cmd.Parameters.Add(new SqlParameter("@productName",dal.ProductName)); cmd.Parameters.Add(new SqlParameter("@unitprice",dal.Unitprice)); cmd.Parameters.Add(new SqlParameter("@special", dal.Special)); cmd.Parameters.Add(new SqlParameter("@categoryId", dal.CategoryId)); con.Open(); try { cmd.ExecuteNonQuery(); } finally { con.Close(); } } public static void Update(ProductInfo dal) { string sql = "update Product set productName=@productName,unitprice=@unitprice,special=@special,categoryId=@categoryId where productId=@productId"; SqlConnection con = new DBConnection().Con; SqlCommand cmd = con.CreateCommand(); cmd.CommandText = sql; //配参数 cmd.Parameters.Add(new SqlParameter("@productName", dal.ProductName)); cmd.Parameters.Add(new SqlParameter("@unitprice", dal.Unitprice)); cmd.Parameters.Add(new SqlParameter("@special", dal.Special)); cmd.Parameters.Add(new SqlParameter("@categoryId", dal.CategoryId)); cmd.Parameters.Add(new SqlParameter("@productId", dal.ProductId)); con.Open(); try { cmd.ExecuteNonQuery(); } finally { con.Close(); } } public static void Delete(int productId) { string sql = "delete Product where productId=@productId"; SqlConnection con = new DBConnection().Con; SqlCommand cmd = con.CreateCommand(); cmd.CommandText = sql; //配参数 cmd.Parameters.Add(new SqlParameter("@productId", productId)); con.Open(); try { cmd.ExecuteNonQuery(); } finally { con.Close(); } } public ProductOper() { // //TODO: 在此处添加构造函数逻辑 // }}
,8
/Default.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>    管理页面    
特价
非特价
 
/Default.aspx.cs
View Code
using System;using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page{    ///     /// 1,展示产品    ///     private void Bind()    {        gvwProduct.DataSource = ProductOper.GetAll();        gvwProduct.DataBind();    }    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            Bind();        }    }    protected void gvwProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)    {        //删除一行数据        Label productIdLabel = (Label)gvwProduct.Rows[e.RowIndex].FindControl("Label1");        int productId = Convert.ToInt32(productIdLabel.Text);        //调用删除方法        ProductOper.Delete(productId);        //更新数据        Bind();    }    protected void gvwProduct_RowDataBound(object sender, GridViewRowEventArgs e)    {        if (e.Row.RowType == DataControlRowType.DataRow)        {             //给单元格,添加单击事件            e.Row.Cells[6].Attributes.Add("onclick", "return confirm('您确定要删除该行数据!')");        }    }    protected void gvwProduct_RowEditing(object sender, GridViewEditEventArgs e)    {        Label specialLabel = (Label)gvwProduct.Rows[e.NewEditIndex].FindControl("Label4");        Label categoryIdLabel = (Label)gvwProduct.Rows[e.NewEditIndex].FindControl("Label5");        //进入编辑模式        gvwProduct.EditIndex = e.NewEditIndex;  //(普通模式<-)分水岭(->编辑模式)        //更新数据        Bind();        RadioButtonList specialRadioButtonList = (RadioButtonList)gvwProduct.Rows[e.NewEditIndex].FindControl("RadioButtonList1");        DropDownList categoryIdDropDownList = (DropDownList)gvwProduct.Rows[e.NewEditIndex].FindControl("DropDownList1");        specialRadioButtonList.SelectedValue = specialLabel.Text;        categoryIdDropDownList.DataSource = CategoryOper.GetAll();        categoryIdDropDownList.DataTextField = "categoryName";        categoryIdDropDownList.DataValueField = "categoryId";        categoryIdDropDownList.DataBind();        categoryIdDropDownList.SelectedValue = categoryIdLabel.Text;           }    protected void gvwProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)    {        //取消编辑模式        gvwProduct.EditIndex = -1;        //更新数据        Bind();    }    protected void gvwProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)    {        //更新数据        //1,准备条件        Label productIdLabel = (Label)gvwProduct.Rows[e.RowIndex].FindControl("Label6");        TextBox productNameTextBox = (TextBox)gvwProduct.Rows[e.RowIndex].FindControl("TextBox2");        TextBox unitpriceTextBox = (TextBox)gvwProduct.Rows[e.RowIndex].FindControl("TextBox3");        RadioButtonList specialRadioButtonList = (RadioButtonList)gvwProduct.Rows[e.RowIndex].FindControl("RadioButtonList1");        DropDownList categoryIdDropDownList = (DropDownList)gvwProduct.Rows[e.RowIndex].FindControl("DropDownList1");        ProductInfo dal = new ProductInfo() {         ProductId=Convert.ToInt32(productIdLabel.Text),          ProductName=productNameTextBox.Text,           Unitprice=Convert.ToDecimal(unitpriceTextBox.Text),            Special=specialRadioButtonList.SelectedValue,             CategoryId=Convert.ToInt32(categoryIdDropDownList.SelectedValue)        };        //2,调用方法        ProductOper.Update(dal);        //取消编辑模式        gvwProduct.EditIndex = -1;        //更新数据        Bind();    }    protected void gvwProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)    {        gvwProduct.PageIndex = e.NewPageIndex;        //更新数据        Bind();    }}
/Create.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Create.aspx.cs" Inherits="Create" %>    添加页面    
添加商品
产品名称
单价
是否特价
特价
非特价
类别
/Create.aspx.cs
View Code
using System;public partial class Create : System.Web.UI.Page{    ///     /// 1,类别列表    ///     private void Bind()    {        dropCategory.DataSource = CategoryOper.GetAll();        dropCategory.DataTextField = "categoryName";        dropCategory.DataValueField = "categoryId";        dropCategory.DataBind();    }    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            Bind();        }    }    protected void btnAdd_Click(object sender, EventArgs e)    {        ProductInfo dal = new ProductInfo() {         ProductName=txtProductName.Text.Trim(),          Unitprice=Convert.ToDecimal(txtUnitprice.Text.Trim()),           Special=rblSpecial.SelectedValue,            CategoryId=Convert.ToInt32(dropCategory.SelectedValue)        };        //调用添加方法        ProductOper.Add(dal);        Response.Redirect("~/Default.aspx");    }}
 
1.C,资源下载

warn 作者:
出处:
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载于:https://www.cnblogs.com/ylbtech/archive/2013/03/19/2969223.html

你可能感兴趣的文章
51nod 1428 活动安排问题 (贪心+优先队列)
查看>>
如何在maven工程中加载oracle驱动
查看>>
aboutMe
查看>>
【Debug】IAR在线调试时报错,Warning: Stack pointer is setup to incorrect alignmentStack,芯片使用STM32F103ZET6...
查看>>
一句话说清分布式锁,进程锁,线程锁
查看>>
FastDFS使用
查看>>
服务器解析请求的基本原理
查看>>
[HDU3683 Gomoku]
查看>>
下一代操作系统与软件
查看>>
Python IO模型
查看>>
DataGridView的行的字体颜色变化
查看>>
局域网内手机访问电脑网站注意几点
查看>>
[Serializable]的应用--注册码的生成,加密和验证
查看>>
Android-多线程AsyncTask
查看>>
LeetCode【709. 转换成小写字母】
查看>>
CF992E Nastya and King-Shamans(线段树二分+思维)
查看>>
如果没有按照正常的先装iis后装.net的顺序,可以使用此命令重新注册一下:
查看>>
【题解】青蛙的约会
查看>>
autopep8
查看>>
GIT在Linux上的安装和使用简介
查看>>