The GridView control can be set to allow users to delete one or more rows in the grid.
This is enabled basically by providing a command-type button control for each row that, essentially, serves to specify the row to delete.
WARNING: Deleting rows in a database table CANNOT BE UNDONE, which can result in serious data loss. In a real-world scenario, only the database administrator or an authorized user must be granted DELETE permission. The examples provided here are only for learning purposes.
Providing delete controls in the GridView can be done in either of the following ways:
- using the automatic deletion feature of the grid, in which the delete button controls for each row are autogenerated and rendered via a separate CommandField object;
- using customized <asp:Button>, <asp:LinkButton> or <asp:ImageButton> controls that are bound to a field in the data source, and which are rendered either via a ButtonField or in the ItemTemplate of a GridView's TemplateField.
- using a checkbox for each row, enabling users to first select the rows they need to remove. A separate Delete button is then provided to remove the checked rows in a batch. Optional Delete All and Clear All buttons may be provided for added functionalities.
Now let's take a closer look at how all these are done. 