欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-02 20:11:46
1.a,运行效果图 1.b,源代码/app_data/sql-basic.sql 复制代码 代码如下:use mastergoif exists(select * f...

1.a,运行效果图

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

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
出处: