Detailsview Delete

The DetailsView control in ASP.NET generates a user interface that resembles the Form View of a Microsoft Access database. It is commonly used for updating or deleting the currently displayed record, as well as inserting new records. One of the primary uses of the DetailsView control is to facilitate the deletion of records.

AutoGenerateDeleteButton

To enable the delete functionality, you can set the AutoGenerateDeleteButton property of the DetailsView control to true. This will automatically generate a delete button, allowing users to remove the currently displayed record. When the delete button is clicked, the DetailsView control triggers the deletion operation.

AutoGenerateDeleteButton="true"

In order to perform the delete operation, it is important to specify the primary key or a unique identifier for the record to be deleted. This is done by supplying a value for the DetailsView control's DataKeyNames property. The DataKeyNames property specifies the names of the fields in the data source that uniquely identify each record. By setting this property, the DetailsView control can determine the record to be deleted based on the provided key value.

detailsview-delete

The following ASP.NET program shows how to delete a record from database using DetailsView control.

Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DetailsView id="DetailsView1" DataSourceID="SqlDataSource1" DataKeyNames="stor_id" AllowPaging ="true" Runat="server" AutoGenerateDeleteButton="true" /> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>" SelectCommand="select * from [stores]" DeleteCommand="DELETE [stores] WHERE stor_id=@stor_id" /> </div> </form> </body> </html>

Conclusion

Supplying the appropriate value for the DataKeyNames property, developers can enable users to delete records using the DetailsView control. This allows for efficient management of data within the application, providing a familiar and intuitive interface for record deletion.