Using CommandField in a GridView control

Using a <CommandField> element, we can display one or more command buttons in a column of the GridView control. When we use the <CommandField> element tag, command buttons are included in each row of a GridView control. As shown in the picture, the <CommandField> column displays Delete, Edit, Update and Cancel buttons.

screenshot of gridview control with use of element tag

Using the below code, the <CommandField> column displays Delete, Edit, Update and Cancel buttons.

Note: Update and Cancel buttons are displayed only when a user clicks on the Edit button to edit a row. Although a single <CommandField> can display more than one button, it is recommended to create separate command fields for Select, Edit and Delete buttons. The ButtonType property specifies the type of button to be displayed in the GridView control. The valid options are Button, Link or Image.

In the code given below, we declare a GridView control and set the AutoGenerateColumns property to 'false' and then add <CommandField> element within the <Columns> element.

<asp:CommandField> element to display buttons in each row of the GridView control. Observe that the ButtonType property of CommandField is set as a hyperlink.

<asp:GridView ID="GridView1" DataSourceId="MyDataSource"   DataKeyNames="Code"
AutoGenerateColumns="false"   runat="server">
	<asp:CommandField ButtonType="Link" ShowEditButton="true" 
    ShowDeleteButton="true"  ShowCancelButton="true" />
	<asp:BoundField  DataField="Code" HeaderText="Code" />
	<asp:BoundField  DataField="Name" HeaderText="Name" />
	<asp:BoundField  DataField="Description" HeaderText="Description" />
<asp:SqlDataSource ID="MyDataSource"  
SelectCommand="SELECT * FROM Sample" 
UpdateCommand="Update SAMPLE SET Name=@Name,Description=@Description Where Code=@Code"
DeleteCommand="Delete SAMPLE Where Code=@Code" runat="server"/>