Deleting data from the DataGrid is not as complex as updating it. Because no item is being edited directly and there is only an indication that the row should be deleted, entering and exiting an editing mode is unnecessary. Code Listing 3-14 is a modified version of Code Listing 3-13 that allows only the deletion of items. Notice that the way a LinkButton is displayed for deleting is the inclusion of a ButtonColumn with the CommandName attribute for the buttons set to Delete. This indicates to the DataGrid to fire the event handler specified in its OnDeleteCommand attribute.
Code Listing 3-14: DataGridDelete.aspx
<%@Import namespace="System.Data" %>
<script language="C#" runat="server">
DataTable data;
protected void Page_Load(object o, EventArgs e) {
GetData();
datagrid1.DataSource = data;
if(!IsPostBack) {
datagrid1.DataBind();
}
}
void DeleteRow(object o, DataGridCommandEventArgs e) {
DataRow row = data.Rows.Find(e.Item.Cells[1].Text);
if(row != null) {
data.Rows.Remove(row);
}
data.AcceptChanges();
datagrid1.DataBind();
Session["data"] = data;
}
DataTable GetData() {
data = Session["data"] as DataTable;
if(data != null) {
return data;
}
data = new DataTable();
DataColumn primaryColumn
= new DataColumn("carid", typeof(Int32));
data.Columns.Add(primaryColumn);
data.Columns.Add(new DataColumn("year", typeof(Int32)));
data.Columns.Add(new DataColumn("make", typeof(string)));
data.Columns.Add(new DataColumn("model", typeof(string)));
DataRow dr;
dr = data.NewRow();
dr[0] = 1; dr[1] = 1998; dr[2] = "Isuzu"; dr[3] = "Trooper";
data.Rows.Add(dr);
dr = data.NewRow();
dr[0] = 2; dr[1] = 2000; dr[2] = "Honda"; dr[3] = "Civic";
data.Rows.Add(dr);
DataColumn[] primaryColumns = new DataColumn[1];
primaryColumns[0] = primaryColumn;
data.PrimaryKey = primaryColumns;
Session["data"] = data;
return data;
}
</script>
<form runat="server">
<asp:DataGrid runat="server" DataKeyField="carid"
AutoGenerateColumns="false" OnDeleteCommand="DeleteRow">
<Columns>
<asp:ButtonColumn CommandName="Delete" Text="Delete" />
<asp:BoundColumn DataField="carid" ReadOnly="true"
HeaderText="id" />
<asp:BoundColumn DataField="year" HeaderText="year" />
<asp:BoundColumn DataField="make" HeaderText="make" />
<asp:BoundColumn DataField="model" HeaderText="model" />
</Columns>
</asp:DataGrid><br/>
</form>