New to Telerik UI for ASP.NET AJAX? Start a free 30-day trial
Delete Records Overview
This is a common task that can be accomplished by placing GridButtonColumn with CommandName= "Delete" in the grid body.Basically, there are two available options:
-
Perform the delete operation automatically by enabling automatic delete through a DataSource control (see this online demo for more details).
-
Execute the delete operation manually wiring the ItemCommand/DeleteCommand event of the control.
The code section below demonstrates the second case. In this example the grid data source is stored in a Session variable:
ASP.NET
<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server" OnDeleteCommand="RadGrid1_DeleteCommand"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView AutoGenerateColumns="False" DataKeyNames="CustomerID">
<Columns>
<telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="DeleteColumn" />
<telerik:GridBoundColumn HeaderText="CompanyName" DataField="CompanyName" UniqueName="CompanyName" />
<telerik:GridBoundColumn HeaderText="ContactName" DataField="ContactName" UniqueName="ContactName" />
<telerik:GridEditCommandColumn UniqueName="EditCommandColumn" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
In the code-behind you should handle properly the RadGrid1_DeleteCommand event.
C#
private void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
OleDbConnection MyOleDbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("~/Grid/Data/Access/Nwind.mdb"));
OleDbDataAdapter MyOleDbDataAdapter = new OleDbDataAdapter();
MyOleDbDataAdapter.SelectCommand = new OleDbCommand("SELECT TOP 10 CustomerID,CompanyName, ContactName FROM Customers", MyOleDbConnection);
DataTable myDataTable;
if (Session["DataSource"] != null)
{
myDataTable = (DataTable)Session["DataSource"];
}
else
{
myDataTable = new DataTable();
MyOleDbConnection.Open();
try
{
MyOleDbDataAdapter.Fill(myDataTable);
}
finally
{
MyOleDbConnection.Close();
}
myDataTable.PrimaryKey = new DataColumn[] { myDataTable.Columns["CustomerID"] };
Session["DataSource"] = myDataTable;
}
RadGrid1.DataSource = myDataTable;
}
private void RadGrid1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
string ID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CustomerID"].ToString();
DataTable table = (DataTable)Session["DataSource"];
if (table.Rows.Find(ID) != null)
{
table.Rows.Find(ID).Delete();
table.AcceptChanges();
Session["DataSource"] = table;
}
}