ASP.NET GridView: cómo editar y eliminar registros de datos

Hola, he usado gridview para crear una tabla. ¿Hay alguna manera de implementar editar y eliminar? Lo he hecho en PHP antes. El método que me gustaría usar es crear dos columnas más en la tabla con botones de edición y eliminación en cada fila. Luego, cuando los botones se presiona, pasa la ‘id’ a través de la URL y puede editarse o eliminarse. No estoy seguro de cómo hacer esto en webforms asp.net. A continuación está mi código para la tabla. Gracias.

      

 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(); 

El GridView es compatible con esas operaciones. Puede agregar un CommandField que contendrá los botones de comando o LinkButtons (puede elegir el tipo de botón y asignar el texto de cada botón). El campo patientID debe incluirse en la propiedad DataKeyNames de GridView, para recuperarlo cuando llegue el momento de actualizar o eliminar el registro en la base de datos.

     ...  

A continuación, deberá controlar algunos eventos en código subyacente:

 // 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(); } 

Como los datos deben estar vinculados a GridView al final de cada uno de esos manejadores de eventos, puede hacerlo en una función de utilidad BindData , que también debe BindData cuando la página se carga inicialmente:

 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: