Grid View: To delete a record in Grid View binded with SQL Datasource
Rate this content:                         
Dear Reader,

To delete a record in Grid View binded with SQL Datasource

 

Following code segment will help you do that

 

I have consider the sample by taking the Northwind database in SQL Server

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"

DataSourceID="SqlDataSource1" OnRowDeleting="GridView_Delete" AutoGenerateDeleteButton="true">

<Columns>

<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" SortExpression="CategoryID" />

<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />

<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

SelectCommand="SELECT * FROM [Categories]"

DeleteCommand="Delete from Categories where CategoryID = @CategoryID">

</asp:SqlDataSource>

 

In the above code DataKeyName is used to delete the category. Inorder to delete the data you have to specify the delete command.

 

In order to handle customer operation before deleting you can do that with OnRowDeleting Event.

 

like

 

protected void GridView_Delete(object sender, GridViewDeleteEventArgs e)

{

     Response.Write(e.Keys[0]);

     e.Cancel = true;

}

 

Here Keys will help to get the key id of the selected row.

   © 2009 Development Next. All Rights Reserved. | Terms of Use | Trademarks