In this example, when the page is presented, there is an additional column at the left of the table that has a link for each row. Clicking this link deletes that row from the database.
To delete rows from a database
<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SQL" %>
Within the <script language="C#" runat="server"> tag, this example implements three functions: Page_Load, MyDataGrid_Delete, and BindGrid. These functions are described in more detail in the steps that follow.
<script language="C#" runat="server"> SQLConnection myConnection;
public void MyDataGrid_Delete(Object sender, DataGridCommandEventArgs E) {
String deleteCmd = "DELETE from Authors where au_id = @Id"; SQLCommand myCommand = new SQLCommand(deleteCmd, myConnection); myCommand.Parameters.Add(new SQLParameter("@Id", SQLDataType.VarChar, 11));
myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
myCommand.ActiveConnection.Open();
try { int rowsAffected = 0; myCommand.Execute(ref rowsAffected); Message.InnerHtml = "<b>Record Deleted</b><br>" + deleteCmd; } catch (SQLException) { Message.InnerHtml = "ERROR: Could not delete record"; Message.Style["color"] = "red"; }
myCommand.ActiveConnection.Close();
BindGrid(); }
<body style="font: 10pt verdana"> <form runat="server"> <h3><font face="Verdana">Deleting a Row of Data</font></h3> <span id="Message" MaintainState="false" style="font: arial 11pt;" runat="server"/><p> <ASP:DataGrid id="MyDataGrid" runat="server" Width="800" BackColor="#ccccff" BorderColor="black" ShowFooter="false" CellPadding=3 CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd" DataKeyField="au_id" OnDeleteCommand="MyDataGrid_Delete" > <property name="Columns"> <asp:ButtonColumn Text="Delete Author" Command="Delete"/> </property> </ASP:DataGrid> </form> </body>
To see this example run, go to the ASP+ Quick Start and run sample DataGrid10.aspx.