Using Command buttons in DetailsView control

The DetailsView control provides command buttons for the user to edit and delete data. The command buttons for a DetailsView control are similar to the command buttons for a Gridview control. Note that the DetailsView control does not provide a Select button which the GridView control provides.

The DetailsView control provides edit, delete, update and cancel buttons. In addition, the DetailsView control lets the user insert data and provides two more buttons - New button and the Insert button. The New button places the DetailsView control in Insert mode, and the Insert button accepts the data entered by the user and saves it to the data source.

There are two ways to provide the command buttons for a DetailsView control. The easiest way is to use the AutoGenerate buttons using the below attributes like:

The AutoGenerateInsertButton attribute to generate a New button.
The AutoGenerateEditButton attribute to generate a Edit button.
The AutoGenerateDeletebutton attribute to generate a Delete button.

The below code displays Edit, New and Delete buttons in a DetailsView control
<asp:DetailsView ID="DetailsView1" runat="server"  AutoGenerateRows="true" 
   AllowPaging="true" DataKeyNames="Code" 
   DataSourceID="MyDataSource"   
   AutoGenerateInsertButton="true" 
   AutoGenerateDeleteButton="true"
   AutoGenerateEditButton="true">
   </asp:DetailsView>
   <asp:SqlDataSource ID="MyDataSource"  
   ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT * FROM Sample" 
UpdateCommand="Update SAMPLE SET Name=@Name,description=@description Where Code=@Code"
DeleteCommand="Delete SAMPLE Where Code=@Code" 
InsertCommand="Insert SAMPLE(Code,Name,description) VALUES(@Code,@Name,@description)"
runat="server"/>


When the user presses the edit button, the DetailsView control is placed in the Edit mode and facilitates the editing of data and the Update button is displayed. After user presses the Update button, the modified data is updated to the data source and DetailsView control is returned to ReadOnly mode.

When the user presses the Delete button, the current item is deleted and the DetailsView control returns back to the ReadOnly mode.

When the user presses the New button, the DetailsView control is placed in Insert mode and the Insert button is displayed. After user enters the data and clicks the Insert button, the data is added to the data source and the DetailsView control is returned to ReadOnly mode.

The Cancel button is displayed in Edit or Insert mode, and when pressed cancels the operation and returns the DetailsView control to readOnly mode.

output of DetailsView control Command buttons