ASP.NET GridView:如何编辑和删除数据记录

您好我使用gridview创建一个表。 有没有办法实现编辑和删除。 我以前用PHP做过。 我想要使​​用的方法是在表格中再创建两列,每行都有编辑和删除按钮。 然后,当单击按钮时,它会通过URL传递“id”并能够编辑或删除。 不确定如何在asp.net webforms中执行此操作。 下面是我的表格代码。 谢谢。

      

 SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); conn.Close(); GridView1.DataSource = dt; GridView1.DataBind(); 

GridView支持这些操作。 您可以添加一个CommandField ,它将包含命令按钮或LinkBut​​tons(您可以选择按钮类型并指定每个按钮的文本)。 patientID字段应包含在GridView的DataKeyNames属性中,以便在更新或删除数据库中的记录时检索它。

     ...  

然后,您需要在代码隐藏中处理一些事件:

 // The RowEditing event is called when data editing has been requested by the user // The EditIndex property should be set to the row index to enter edit mode protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindData(); } // The RowCancelingEdit event is called when editing is canceled by the user // The EditIndex property should be set to -1 to exit edit mode protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindData(); } // The RowUpdating event is called when the Update command is selected by the user // The EditIndex property should be set to -1 to exit edit mode protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { int patientID = (int)e.Keys["patientID"] string surgery = (string)e.NewValues["surgery"]; string location = (string)e.NewValues["location"]; // Update here the database record for the selected patientID GridView1.EditIndex = -1; BindData(); } // The RowDeleting event is called when the Delete command is selected by the user protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int patientID = (int)e.Keys["patientID"] // Delete here the database record for the selected patientID BindData(); } 

由于数据必须绑定到每个事件处理程序末尾的GridView,因此您可以在BindData实用程序函数中执行此操作,该函数也应在最初加载页面时调用:

 private void BindData() { SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); conn.Close(); GridView1.DataSource = dt; GridView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } 
 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Configuration; using System.Data.SqlClient; namespace FinalYearProject { public partial class MBooking : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.BindGrid(); } } private void BindGrid() { string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.Parameters.AddWithValue("@Action", "SELECT"); using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } } protected void Insert(object sender, EventArgs e) { string Username = txtUsername.Text; string Provincename = txtProvinceName.Text; string Cityname = txtCityname.Text; string Number = txtNumber.Text; string Name = txtName.Text; string ContentType = txtContentType.Text; string Data = txtData.Text; string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Action", "INSERT"); cmd.Parameters.AddWithValue("@Username", Username); cmd.Parameters.AddWithValue("@Provincename ", Provincename); cmd.Parameters.AddWithValue("@Cityname", Cityname); cmd.Parameters.AddWithValue("@Number", Number); cmd.Parameters.AddWithValue("@Name", Name); cmd.Parameters.AddWithValue("@ContentType", ContentType); //cmd.Parameters.AddWithValue("@Data", Data); cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } protected void OnRowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; this.BindGrid(); } protected void OnRowCancelingEdit(object sender, EventArgs e) { GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string Username = (row.FindControl("txtUserName") as TextBox).Text; string Provincename = (row.FindControl("txtProvincename") as TextBox).Text; string Cityname = (row.FindControl("txtCityname") as TextBox).Text; string Number = (row.FindControl("txtNumber") as TextBox).Text; string Name = (row.FindControl("txtName") as TextBox).Text; string ContentType = (row.FindControl("txtContentType") as TextBox).Text; string Data = (row.FindControl("txtData") as TextBox).Text; string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Action", "UPDATE"); cmd.Parameters.AddWithValue("@BId", BId); cmd.Parameters.AddWithValue("@Username", Username); cmd.Parameters.AddWithValue("@Provincename ", Provincename); cmd.Parameters.AddWithValue("@Cityname", Cityname); cmd.Parameters.AddWithValue("@Number", Number); cmd.Parameters.AddWithValue("@Name", Name); cmd.Parameters.AddWithValue("@ContentType",ContentType) ; cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; //cmd.Parameters.AddWithValue("@ContentType", SqlDbType.VarBinary, -1); //cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary, -1); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } GridView1.EditIndex = -1; this.BindGrid(); } protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; this.BindGrid(); } protected void OnRowDataBound(object sender, GridViewRowEventArgs e) { //if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex) //{ // (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');"; //} } protected void DownloadFile(object sender, EventArgs e) { int id = int.Parse((sender as LinkButton).CommandArgument); byte[] bytes; string fileName, contentType; string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=@BId"; cmd.Parameters.AddWithValue("@BId",id); cmd.Connection = con; con.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { sdr.Read(); bytes = (byte[])sdr["Data"]; contentType = sdr["ContentType"].ToString(); fileName = sdr["Name"].ToString(); } con.Close(); } } Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = contentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e) { int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Customers_CRUD")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Action", "DELETE"); cmd.Parameters.AddWithValue("@BId", BId); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } } } 
 And Store Procedure is: USE [DemoProjet] GO /****** Object: StoredProcedure [dbo].[Customers_CRUD] Script Date: 11-Jan-17 2:57:38 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[Customers_CRUD] @Action VARCHAR(10) ,@BId INT = NULL ,@Username VARCHAR(50) = NULL ,@Provincename VARCHAR(50) = NULL ,@Cityname VARCHAR(50) = NULL ,@Number VARCHAR(50) = NULL ,@Name VARCHAR(50) = NULL ,@ContentType VARCHAR(50) = NULL ,@Data VARBINARY(MAX) = NULL AS BEGIN SET NOCOUNT ON; --SELECT IF @Action = 'SELECT' BEGIN SELECT BId , Username,Provincename,Cityname,Number,Name,ContentType, Data FROM tblbooking END --INSERT IF @Action = 'INSERT' BEGIN INSERT INTO tblbooking(Username,Provincename,Cityname,Number,Name,ContentType, Data) VALUES (@Username ,@Provincename ,@Cityname ,@Number ,@Name ,@ContentType ,@Data) END --UPDATE IF @Action = 'UPDATE' BEGIN UPDATE tblbooking SET Username = @Username,Provincename = @Provincename,Cityname = @Cityname,Number = @Number,Name = @Name,ContentType = @ContentType,Data = @Data WHERE BId = @BId END --DELETE IF @Action = 'DELETE' BEGIN DELETE FROM tblbooking WHERE BId = @BId END END GO 
 And Aspx page is: <%@ Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %>                                                                                  
Username:
Provincename:
Cityname:
Number:
Name:
ContentType:
Data: