Como Eliminar un Row de un Gridview en C#

El siguiente formato HTML consiste en un GridView de C# con dos columnas BoundField y una columna CommandField así:

<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns ="false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Item" HeaderText="Item" />
        <asp:BoundField DataField="Price" HeaderText="Price" />
        <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
    </Columns>
</asp:GridView>

Dentro del evento de carga de la página , el ASP.Net GridView se rellena usando un DataTable y DataTable se guarda en la variable ViewState.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Price") });
        dt.Rows.Add("Shirt", 450);
        dt.Rows.Add("Jeans", 3200);
        dt.Rows.Add("Trousers", 1900);
        dt.Rows.Add("Tie", 185);
        dt.Rows.Add("Cap", 100);
        dt.Rows.Add("Hat", 120);
        dt.Rows.Add("Scarf", 290);
        dt.Rows.Add("Belt", 150);
        ViewState["dt"] = dt;
        BindGrid();
    }
}
protected void BindGrid()
{
    GridView1.DataSource = ViewState["dt"] as DataTable;
    GridView1.DataBind();
}



Aplicando el cuadro de confirmación JavaScript para GridView CommandField Borrar Button

Dentro del controlador de eventos OnRowDataBound, un bucle se ejecuta en los controles Button del GridView. Si el CommandName del botón es Eliminar continua mostrando el cuadro de confirmación se asignando su atributo OnClic.

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string item = e.Row.Cells[0].Text;
        foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
        {
            if (button.CommandName == "Delete")
            {
                button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
            }
        }
    }
}
Elimine el ASP.Net GridView Fila usando CommandField y eventos OnRowDeleting

Cuando se hace clic en el botón Eliminar, se ejecuta el controlador de eventos OnRowDeleting. Dentro del controlador de eventos OnRowDeleting, el Índice del GridView fila se determina y se y se utiliza para eliminar la Línea de DataTable.

Por último, el DataTable se guarda de nuevo a la ViewState y el GridView está nuevamente poblada. A continuación puedes visualizar como se Elimina un Row de un GridView de forma fácil.


protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int index = Convert.ToInt32(e.RowIndex);
    DataTable dt = ViewState["dt"] as DataTable;
    dt.Rows[index].Delete();
    ViewState["dt"] = dt;
    BindGrid();
}
Share: