asp.net中gridview的查询、分页、编辑更新、删除的实例代码

 更新时间:2021年9月22日 10:16  点击:1951

1.A,运行效果图

1.B,源代码
/App_Data/sql-basic.sql

复制代码 代码如下:

use master
go
if exists(select * from sysdatabases where name='db1')
begin
    drop database db1
end
go
create database db1
go
use db1
go
-- ================================
-- 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 category
select productid,productname,unitprice,special,categoryid from product

,2
/App_Code/
/App_Code/DBConnection.cs

复制代码 代码如下:

using System.Data.SqlClient;
/// <summary>
///DBConnection 的摘要说明
///数据连接类
/// </summary>
public class DBConnection
{
    SqlConnection con = null;

    public DBConnection()
    {
        //创建连接对象
        con = new SqlConnection("Server=.;Database=db1;Uid=sa;pwd=sa");
    }

    /// <summary>
    /// 数据连接对象
    /// </summary>
    public SqlConnection Con
    {
        get { return con; }
        set { con = value; }
    }
}

/App_Code/CategoryInfo.cs
/App_Code/CategoryOper.cs
/App_Code/ProductInfo.cs

复制代码 代码如下:

using System;

/// <summary>
///ProductInfo 的摘要说明
///产品实体类
/// </summary>
public class ProductInfo
{
    //1,Attributes
    int productId;
    string productName;
    decimal unitprice;
    string special;
    int categoryId;

    public ProductInfo()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    //3,

    /// <summary>
    /// 产品编号【PK】
    /// </summary>
    public int ProductId
    {
        get { return productId; }
        set { productId = value; }
    }
    /// <summary>
    /// 产品名称
    /// </summary>
    public string ProductName
    {
        get { return productName; }
        set { productName = value; }
    }
    /// <summary>
    /// 单位价格
    /// </summary>
    public decimal Unitprice
    {
        get { return unitprice; }
        set { unitprice = value; }
    }
    /// <summary>
    /// 是否为特价【C】(特价、非特价)
    /// </summary>
    public string Special
    {
        get { return special; }
        set { special = value; }
    }
    /// <summary>
    /// 类编编号【FK】
    /// </summary>
    public int CategoryId
    {
        get { return categoryId; }
        set { categoryId = value; }
    }
}

/App_Code/ProductOper.cs

复制代码 代码如下:

using System;
using System.Collections.Generic;

using System.Data.SqlClient;
/// <summary>
///ProductOper 的摘要说明
/// </summary>
public class ProductOper
{
    /// <summary>
    /// 1,GetAll
    /// </summary>
    /// <returns></returns>
    public static IList<ProductInfo> GetAll()
    {
        IList<ProductInfo> dals = new List<ProductInfo>();
        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

复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>管理页面</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:HyperLink ID="hlCreate" runat="server" Text="添加" NavigateUrl="Create.aspx"></asp:HyperLink>
    <asp:GridView ID="gvwProduct" runat="server" AutoGenerateColumns="False"
            onrowcancelingedit="gvwProduct_RowCancelingEdit"
            onrowdatabound="gvwProduct_RowDataBound" onrowdeleting="gvwProduct_RowDeleting"
            onrowediting="gvwProduct_RowEditing"
            onrowupdating="gvwProduct_RowUpdating" Width="700px" AllowPaging="True"
            onpageindexchanging="gvwProduct_PageIndexChanging" PageSize="5">
        <Columns>
            <asp:TemplateField HeaderText="产品编号">
                <EditItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("productId") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("productId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="产品名称">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("productName") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("productName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="单价">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("unitprice") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("unitprice") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="是否特价">
                <EditItemTemplate>
                    <asp:RadioButtonList ID="RadioButtonList1" runat="server"
                        RepeatDirection="Horizontal" RepeatLayout="Flow">
                        <asp:ListItem>特价</asp:ListItem>
                        <asp:ListItem>非特价</asp:ListItem>
                    </asp:RadioButtonList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("special") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="类别编号">
                <EditItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("categoryId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
        </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

/Default.aspx.cs

复制代码 代码如下:

using System;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// 1,展示产品
    /// </summary>
    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

复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Create.aspx.cs" Inherits="Create" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>添加页面</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:HyperLink ID="hlDefault" runat="server" Text="产品列表" NavigateUrl="~/Default.aspx"></asp:HyperLink>
    <fieldset>
    <legend>添加商品</legend>
    <table width="500px">
     <tr>
    <td>产品名称</td>
    <td>
        <asp:TextBox ID="txtProductName" runat="server"></asp:TextBox>
         </td>
    <td></td>
    </tr>
     <tr>
    <td>单价</td>
    <td>
        <asp:TextBox ID="txtUnitprice" runat="server"></asp:TextBox>
         </td>
    <td></td>
    </tr>
     <tr>
    <td>是否特价</td>
    <td>
        <asp:RadioButtonList ID="rblSpecial" runat="server"
            RepeatDirection="Horizontal" RepeatLayout="Flow">
            <asp:ListItem>特价</asp:ListItem>
            <asp:ListItem Selected="True">非特价</asp:ListItem>
        </asp:RadioButtonList>
         </td>
    <td></td>
    </tr>
     <tr>
    <td>类别</td>
    <td>
        <asp:DropDownList ID="dropCategory" runat="server">
        </asp:DropDownList>
         </td>
    <td></td>
    </tr>
     <tr>
    <td></td>
    <td>
        <asp:Button ID="btnAdd" runat="server" Text="添加" onclick="btnAdd_Click" />
         </td>
    <td></td>
    </tr>
    </table>
    </fieldset>
    </div>
    </form>
</body>
</html>

/Create.aspx.cs

复制代码 代码如下:

using System;

public partial class Create : System.Web.UI.Page
{
    /// <summary>
    /// 1,类别列表
    /// </summary>
    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");
    }
}


作者:ylbtech
出处:http://ylbtech.cnblogs.com/

[!--infotagslink--]

相关文章

  • php KindEditor文章内分页的实例方法

    我们这里介绍php与KindEditor编辑器使用时如何利用KindEditor编辑器的分页功能实现文章内容分页,KindEditor编辑器在我们点击分页时会插入代码,我们只要以它为分切符,就...2016-11-25
  • Mybatis Plus select 实现只查询部分字段

    这篇文章主要介绍了Mybatis Plus select 实现只查询部分字段的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-01
  • 自己动手写的jquery分页控件(非常简单实用)

    最近接了一个项目,其中有需求要用到jquery分页控件,上网也找到了需要分页控件,各种写法各种用法,都是很复杂,最终决定自己动手写一个jquery分页控件,全当是练练手了。写的不好,还请见谅,本分页控件在chrome测试过,其他的兼容性...2015-10-30
  • jquery实现的伪分页效果代码

    本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
  • MyBatisPlus-QueryWrapper多条件查询及修改方式

    这篇文章主要介绍了MyBatisPlus-QueryWrapper多条件查询及修改方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2022-06-27
  • Oracle使用like查询时对下划线的处理方法

    这篇文章主要介绍了Oracle使用like查询时对下划线的处理方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-16
  • 解决mybatis-plus 查询耗时慢的问题

    这篇文章主要介绍了解决mybatis-plus 查询耗时慢的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-04
  • vue.js 表格分页ajax 异步加载数据

    Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.这篇文章主要介绍了vue.js 表格分页ajax 异步加载数据的相关资料,需要的朋友可以参考下...2016-10-20
  • Springboot如何使用mybatis实现拦截SQL分页

    这篇文章主要介绍了Springboot使用mybatis实现拦截SQL分页,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-19
  • PHP 一个完整的分页类(附源码)

    在php中要实现分页比起asp中要简单很多了,我们核心就是直接获取当前页面然后判断每页多少再到数据库中利用limit就可以实现分页查询了,下面我来详细介绍分页类实现程序...2016-11-25
  • MySQL中在查询结果集中得到记录行号的方法

    如果需要在查询语句返回的列中包含一列表示该条记录在整个结果集中的行号, ISO SQL:2003 标准提出的方法是提供 ROW_NUMBER() / RANK() 函数。 Oracle 中可以使用标准方法(8i版本以上),也可以使用非标准的 ROWNUM ; MS SQL...2015-03-15
  • Node实现搜索框进行模糊查询

    这篇文章主要为大家详细介绍了Node实现搜索框进行模糊查询,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-06-28
  • jquery实现的伪分页效果代码

    本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
  • Mybatis用注解写in查询的实现

    这篇文章主要介绍了Mybatis用注解写in查询的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-13
  • PHP+Mysql+jQuery查询和列表框选择操作实例讲解

    本文讲解如何通过ajax查询mysql数据,并将返回的数据显示在待选列表中,再通过选择最终将选项加入到已选区,可以用在许多后台管理系统中。本文列表框的操作依赖jquery插件。HTML <form id="sel_form" action="post.php" me...2015-10-23
  • Element-ui 自带的两种远程搜索(模糊查询)用法讲解

    这篇文章主要介绍了Element-ui 自带的两种远程搜索(模糊查询)用法讲解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-29
  • 基于jquery实现表格无刷新分页

    这篇文章主要介绍了基于jquery实现表格无刷新分页,功能实现了前端排序功能,增加了前端搜索功能,感兴趣的小伙伴们可以参考一下...2016-01-08
  • C#实现3步手动建DataGridView的方法

    这篇文章主要介绍了C#实现3步手动建DataGridView的方法,实例分析了C#实现手动创建DataGridView的原理与技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • AngularJS实现分页显示数据库信息

    这篇文章主要为大家详细介绍了AngularJS实现分页显示数据库信息效果的相关资料,感兴趣的小伙伴们可以参考一下...2016-07-06
  • Mybatis和Mybatis-Plus时间范围查询方式

    这篇文章主要介绍了Mybatis和Mybatis-Plus时间范围查询方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-06