在ASP.NET中實現選中、編輯和刪除GridView資料項

2020-09-19 16:01:01

先上效果圖:
在這裡插入圖片描述
我所用的資料庫是這個樣子的:
在這裡插入圖片描述

程式碼,分別是.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