Manish Dalal's blog

Exploring .net!

Silverlight Business Application Part 2: Delete item

This is part two of Building Business Application with Silverlight series that showcases the basic building blocks of a data centric application. 

Deleting an item is quite similar to adding an item. Instead of adding new item to the collection, we just remove the selected item from the collection.

To allow user to delete the selected person, add new Delete button to StackPanel

<StackPanel Orientation="Horizontal">
    <!--<Button x:Name="addButton" Content="Add" Margin="5"/>-->
    <Button x:Name="deleteButton" Content="Delete" Margin="5"/>

Now add handler for delete click event in the page.xaml.cs code behind

public Page() {
    this.Loaded += new RoutedEventHandler(Page_Loaded);
    //this.addButton.Click += new RoutedEventHandler(addButton_Click);
    this.peopleDataGrid.KeyDown += new KeyEventHandler(peopleDataGrid_KeyDown);
    this.deleteButton.Click += new RoutedEventHandler(deleteButton_Click);

void deleteButton_Click(object sender, RoutedEventArgs e) {

private void DeletePerson() {
    if (null == this.peopleDataGrid.SelectedItem) {
    Person person = this.peopleDataGrid.SelectedItem as Person;
    if (null == person) {

F5 and run the application, try to add some new items and delete them


You can also allow user to delete using key board

void peopleDataGrid_KeyDown(object sender, KeyEventArgs e) {
    //if (Key.Insert == e.Key) {
    //    _data.Add(new Person());
    if (Key.Delete == e.Key) {

On problem with above solution is the fact that user can delete our empty row at the end and then they have no way of adding new item! Lets fix that by checking for removal of emptyPerson in the People class

protected override void RemoveItem(int index) {
    Person personToRemove = this[index] as Person;
    if (emptyPerson != personToRemove) {

Now when user tries to remove last empty row used to add new item, we detect it and prevent removal of emptyPerson.

In a real application, DeletePerson will eventually call backend application server to remove the item from database. A nice enhancement would be to provide ability recover deleted item, similar to Recycle Bin functionality, by maintaining list of deleted items on the client side.

One alternative to deleting immediately is to collect deleted items in a separate list and batch delete them when user elects to save changes. You can either maintain separate list or keep item in the same list and just change the state to mark them as deleted. This can be further combined with data binding to make DataGrid row read only and rendered with different color to indicate deleted row status. This gives user visibility of all changes and provides a chance to change mind before committing!

At this point we have a complete functioning application that allow user to add data, update data and delete. Next we will take on validation.


No Comments