Search code examples
asp.netgridviewcommandfield

Programmatically add OnRowDelete to a GridView


I'm programatically generating GridViews, each GridView has a CommandField with a delete button. How do I programatically add OnDeletingRow so that a function is called when the delete button with the GridView is clicked?

                    GridView gv = new GridView();
                    gv.AutoGenerateColumns = false;
                    gv.ID = "GridView_" + selectedId;
                    gv.DataKeyNames = new string[] {"id"};
                    gv.AllowPaging = false;
                    gv.CellPadding = 3;
                    gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);

                    CommandField commandfieldDeallocate = new CommandField();
                    commandfieldDeallocate.HeaderText = "DELETE NUMBER";
                    commandfieldDeallocate.ShowDeleteButton = true;
                    commandfieldDeallocate.DeleteText = "DELETE";
                    gv.Columns.Add(commandfieldDeallocate);

Solution

  • In C#, you can do it this way:

    gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);
    
    void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Perform deletion
    }