ASP.NET GridView: Comment modifier et supprimer des enregistrements de données

Bonjour, j’ai utilisé gridview pour créer une table. Y a-t-il un moyen d’implémenter éditer et supprimer. Je l’ai déjà fait en PHP. La méthode que je voudrais utiliser est de créer deux colonnes supplémentaires dans le tableau avec les boutons modifier et supprimer sur chaque ligne. Ensuite, lorsque les boutons sont cliqués, il passe l’ID à travers l’URL et peut être modifié ou supprimé. Je ne sais pas trop comment faire cela dans les formulaires Web asp.net. Ci-dessous, mon code pour la table. Je vous remercie.

      

 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 prend en charge ces opérations. Vous pouvez append un CommandField qui contiendra les boutons de commande ou les boutons de liaison (vous pouvez choisir le type de bouton et atsortingbuer le texte de chaque bouton). Le champ patientID doit être inclus dans la propriété DataKeyNames du GridView afin de pouvoir le récupérer lorsque le moment sera venu de mettre à jour ou de supprimer l’enregistrement dans la firebase database.

     ...  

Vous devrez ensuite gérer quelques événements dans code-behind:

 // 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"] ssortingng surgery = (ssortingng)e.NewValues["surgery"]; ssortingng location = (ssortingng)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(); } 

Puisque les données doivent être liées au GridView à la fin de chacun de ces gestionnaires d’événements, vous pouvez le faire dans une fonction d’utilitaire BindData , qui devrait également être appelée lors du chargement initial de la page:

 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() { ssortingng constr = ConfigurationManager.ConnectionSsortingngs["cmt"].ConnectionSsortingng; 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) { ssortingng Username = txtUsername.Text; ssortingng Provincename = txtProvinceName.Text; ssortingng Cityname = txtCityname.Text; ssortingng Number = txtNumber.Text; ssortingng Name = txtName.Text; ssortingng ContentType = txtContentType.Text; ssortingng Data = txtData.Text; ssortingng constr = ConfigurationManager.ConnectionSsortingngs["cmt"].ConnectionSsortingng; 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]); ssortingng Username = (row.FindControl("txtUserName") as TextBox).Text; ssortingng Provincename = (row.FindControl("txtProvincename") as TextBox).Text; ssortingng Cityname = (row.FindControl("txtCityname") as TextBox).Text; ssortingng Number = (row.FindControl("txtNumber") as TextBox).Text; ssortingng Name = (row.FindControl("txtName") as TextBox).Text; ssortingng ContentType = (row.FindControl("txtContentType") as TextBox).Text; ssortingng Data = (row.FindControl("txtData") as TextBox).Text; ssortingng constr = ConfigurationManager.ConnectionSsortingngs["cmt"].ConnectionSsortingng; 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).Atsortingbutes["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; ssortingng fileName, contentType; ssortingng constr = ConfigurationManager.ConnectionSsortingngs["cmt"].ConnectionSsortingng; 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"].ToSsortingng(); fileName = sdr["Name"].ToSsortingng(); } 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]); ssortingng constr = ConfigurationManager.ConnectionSsortingngs["cmt"].ConnectionSsortingng; 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: