Programmatically add OnRowDelete to a GridView

139 Views Asked by At

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

There are 1 best solutions below

2
ConnorsFan On BEST ANSWER

In C#, you can do it this way:

gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);

void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    // Perform deletion
}