在ASP.NET中实现选中、编辑和删除GridView数据项

先上效果图:
在这里插入图片描述
我所用的数据库是这个样子的:
在这里插入图片描述

代码,分别是.aspx文件和.aspx.cs文件,自行复制粘贴使用,注意如果要匹配自己的数据库就要修改数据库连接以及字段名:

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>以编程方式实现选中、编辑和删除GridView数据项</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" 
            CellPadding="4" GridLines="Horizontal" 
            onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
            onrowupdating="GridView1_RowUpdating" PageSize="5" 
            style="font-size: small">
            <RowStyle BackColor="White" ForeColor="#333333" />
            <Columns>
                <asp:BoundField DataField="book_code" HeaderText="图书编号" ReadOnly="True" />
                <asp:BoundField DataField="book_name" HeaderText="图书名称" />
                <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
                <asp:CommandField ButtonType="Image" CancelImageUrl="~/Images/BtnCancel.gif" 
                    EditImageUrl="~/Images/BtnUpdate.gif" HeaderText="编辑" ShowEditButton="True" 
                    UpdateImageUrl="~/Images/BtnSave.gif" />
                <asp:TemplateField HeaderText="删除" ShowHeader="False">
                    <ItemTemplate>
                        <asp:ImageButton ID="ImageButton1" runat="server" CommandName="Delete" 
                            ImageUrl="~/Images/BtnDelete.gif" 
                            onclientclick="return confirm('确定删除吗?');" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
        <br />    
    </div>
    </form>
</body>
</html>

Default.aspx.cs文件

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//引入命名空间
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //调用自定义方法绑定数据到控件
            BindData();
        }
    }
    public void BindData()
    {
        //定义数据库连接字符串
        string strCon = @"Server = DEITIVOD; Database = db_LibraryMS; User Id = sa; pwd = admin";
        string sqlstr = "select book_code,book_name from tb_bookinfo";//定义执行查询操作的SQL语句
        SqlConnection con = new SqlConnection(strCon);//创建数据库连接对象
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);//创建数据适配器
        DataSet ds = new DataSet();//创建数据集
        da.Fill(ds);//填充数据集
                    //设置GridView控件的数据源为创建的数据集ds
        GridView1.DataSource = ds;
        //将数据库表中的主键字段放入GridView控件的DataKeyNames属性中
        GridView1.DataKeyNames = new string[] { "book_code" };
        GridView1.DataBind();//绑定数据库表中数据

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string delete_sql = "delete from tb_bookinfo where book_code='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
        bool delete = ExceSQL(delete_sql);//调用ExceSQL执行删除操作
        if (delete)
        {
            Response.Write("<script language=javascript>alert('删除成功!')</script>");
            BindData();//调用自定义方法重新绑定控件中数据
        }
        else
        {
            Response.Write("<script language=javascript>alert('删除失败!')</script>");
        }
    }
    /// <summary>
    /// 此方法用来执行SQL语句
    /// </summary>
    /// <param name="SqlCom">要执行的SQL语句</param>
    /// <returns></returns>
    public bool ExceSQL(string strSqlCom)
    {
        //定义数据库连接字符串
        string strCon = @"Server = DEITIVOD; Database = db_LibraryMS; User Id = sa; pwd = admin";
        //创建数据库连接对象
        SqlConnection sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom = new SqlCommand(strSqlCom, sqlcon);
        try
        {
            if (sqlcon.State == System.Data.ConnectionState.Closed)//判断数据库是否为连连状态
            { sqlcon.Open(); }
            sqlcom.ExecuteNonQuery();//执行SQL语句
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            sqlcon.Close();//关闭数据库连接
        }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //取得编辑行的关键字段的值
        string bccdID = GridView1.DataKeys[e.RowIndex].Value.ToString();
        //取得文本框中输入的内容
        string bccdName=((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim();
        //定义更新操作的SQL语句
        string update_sql = "update tb_bookinfo set book_name='" + bccdName + "' where book_code='" + bccdID + "'";
        bool update = ExceSQL(update_sql);//调用ExceSQL执行更新操作
        if (update)
        {
            Response.Write("<script language=javascript>alert('修改成功!')</script>");
            //设置GridView控件的编辑项的索引为-1,即取消编辑
            GridView1.EditIndex = -1;
            BindData();
        }
        else
        {
            Response.Write("<script language=javascript>alert('修改失败!');</script>");
        }
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //设置GridView控件的编辑项的索引为-1,即取消编辑
        GridView1.EditIndex = -1;
        BindData();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;//设置编辑页
        BindData();
    }
}

以上代码使用的图片文件在这个链接中可以下载
提取码:0hry

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:设计师小姐姐 返回首页