You can allow users to delete items in a DataList control in a variety of ways. One way is to include a Delete button in an item and to delete that item immediately when the user clicks it.
Another way is to include a checkbox in individual items. Users can then check all the items they want and then click a separate Delete button to delete them in a batch. This is a style used in products such as Microsoft Hotmail.
To allow users to delete items individually
The event-handling method might look like this:
[C#]
protected void DataList1_OnDeleteCommand(object Source,
DataListCommandEventArgs e)
{
string ID = ((TextBox)e.Item.FindControl("CustomerID")).Text;
// Delete item from data source here using ID extracted earlier
DataList1.DataBind(); // Rebind to data source
}
To allow users to delete multiple items in a batch
The following example shows how you can create an event-handling method for a Delete button that deletes items in a batch using the procedure outlined above. The example assumes that you are working with a DataList control called DataList1 and that the CheckBox control in each item is called Check1.
protected void btnDelete_Click(object sender, System.EventArgs e) { int i; for(i=0; i< DataList1.Items.Count; i++){ DataListItem NextItem = DataList1.Items[i]; Boolean DelFlag = ((CheckBox)NextItem.FindControl("Check1")).Checked; if(DelFlag == true){ // Delete item from data source here } DataList1.DataBind(); // Rebind to data source } }
Introduction to the DataList Web Control | Allowing Users to Edit Items | Allowing Users to Select Items | Responding to Button Events in DataList Items