Saturday, December 26, 2020

GridView buttons and commands Delete

 You have a GridView and you want a simple Delete button. What are your options?

Most basic would be to use the CommandField (the Wizard will take you here, too).


Main points are:

In the <asp:Gridview> , after the <columns>, before the <asp:BoundField> items, you would see:

<asp:CommandField ..... (tbd???)


and it is incumbant upon the asp:SqlDataSource to have a section called:

DeleteCommand="" with the actual SQL to be used.


The only other power you have is to include a OnRowDeleted="{create event}" in the <asp:GridView> block, to do something like handle EXCEPTIONS (example: gvResources_RowDeleted).

You can customize how the "Delete" button looks like (Wizard will default to a link that says "Delete" in the same column as Add and Edit, generally in first column) by a bunch of optional properties in the <asp:CommandField> tag:

ButtonType="Image"

DeleteImageUrl="~/Images/deleteIcon.png"

DeleteText="Delete" (default from Wizard)

??? ShowDeleteButton="True" ????


For example, see my Forecast Resources Index page gridview.


The next way to create a "delete button" would be with a ButtonField (or a TemplateField???) but that would be overkill so long as any delete operation can be accomplished with either a SQL statement or even Stored Proc (since the CommandField can also call a stored proc).

However, let's say you prefer to, instead of calling a SQL statement stored in either the ASPX file or SQL Server (for sprocs), but in a data persistence class, maybe a ButtonField is for you.

Seemingly confusingly, to use a ButtonField, you have to specify a handler in the <asp:Gridview block named OnRowCommand="", which sounds like you are using the CommandField!!! 


onrowcommand="CustomersGridView_RowCommand"



<asp:buttonfield buttontype="Button" commandname="DeleteThis" text="Del"/>



.void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)

{
if(e.CommandName=="DeleteThis") { // Convert the row index stored in the CommandArgument // property to an Integer. int index = Convert.ToInt32(e.CommandArgument); // Get the last name of the selected author from the appropriate // cell in the GridView control. GridViewRow selectedRow = GridView1.Rows[index]; TableCell contactName = selectedRow.Cells[1]; ...


    //do delete


GridView1.DataBind();
etc


I learned that if you use the CommandName="Delete" you will get an error b/c of clash with other functionality.....Also remember to rebind the grid.



No comments: