Insert, Update and Delete in Silverlight DataGrid using ADO.NET

Introduction

 
This article is in continuation of the previous one in which I discussed how to create ADO.NET Data Service and access Database using Silverlight 2. Here I am going to show how to perform Insert, Update, and Delete in Silverlight Datagrid using ADO.NET Data Service.
 
1. Create a class of the Entities type
  1. TestEntities proxy;   
2. Create a variable to track if DataGrid is in Edit mode
  1. private bool inEdit; 
3. Create Page_Loaded event to initailize the ADO.NET Data Service
  1. void Page_Loaded(object sender, RoutedEventArgs e) {  
  2.   proxy = new TestEntities(new Uri("WebDataService.svc", UriKind.Relative));  
4. Create Events for the DataGrid
  1. < my: DataGrid x: Name = "dataGrid"  
  2. Margin = "10"  
  3. AutoGenerateColumns = "True"  
  4. AutoGeneratingColumn = "OnGeneratedColumn"  
  5. BeginningEdit = "dataGrid_BeginningEdit"  
  6. CommittingEdit = "dataGrid_CommittingEdit"  
  7. CancelingEdit = "dataGrid_CancelingEdit"  
  8. KeyDown = "dataGrid_KeyDown" / > 
5. AttachTo method is used when an entity exists in the store already and you would want the DataServiceContext to track that entity. Use AddObject or AddTo method when a new entity is created and want the Context to track the entity. Write the Event Handelers for DataGrid Events
  1. private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) {  
  2.   inEdit = true;  
  3. }  
  4. private void dataGrid_CancelingEdit(object sender, DataGridEndingEditEventArgs e) {  
  5.   inEdit = false;  
  6. }  
  7. private void dataGrid_CommittingEdit(object sender, DataGridEndingEditEventArgs e) {  
  8.   //Attach the object to the context.  
  9.   try {  
  10.     proxy.AttachTo("Users", dataGrid.SelectedItem);  
  11.   }  
  12.   catch {}  
  13.   proxy.UpdateObject(e.Row.DataContext);  
6. Create a ObservableCollection
  1. /// <summary>  
  2. /// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.  
  3. /// </summary>  
  4. ObservableCollection < Users > BoundData {  
  5.   get {  
  6.     return (dataGrid.ItemsSource as ObservableCollection < Users > );  
  7.   }  
7. KeyDown Event of the DataGrid to Insert, Update and Delete rows
  1. private void dataGrid_KeyDown(object sender, KeyEventArgs e) {  
  2.   if (!inEdit) {  
  3.     TextBlockStatus.Text = "";  
  4.     if (e.Key == Key.Delete) {  
  5.       if (dataGrid.SelectedItem != null) {  
  6.         //Attach the object to the context.  
  7.         try {  
  8.           proxy.AttachTo("Users", dataGrid.SelectedItem);  
  9.         }  
  10.         catch(Exception ex) {  
  11.           TextBlockStatus.Text = ex.Message;  
  12.         }  
  13.         proxy.DeleteObject(dataGrid.SelectedItem);  
  14.         // Remove from the bound collection, disappears from DataGrid.  
  15.         BoundData.Remove(dataGrid.SelectedItem as Users);  
  16.       }  
  17.     }  
  18.     else if (e.Key == Key.Insert) {  
  19.       Users u = new Users() {  
  20.         FirstName = "",  
  21.         LastName = ""  
  22.       };  
  23.       int index = BoundData.IndexOf(dataGrid.SelectedItem as Users);  
  24.       BoundData.Insert(index, u);  
  25.       dataGrid.SelectedIndex = index;  
  26.       dataGrid.BeginEdit();  
  27.       proxy.AddObject("Users", u);  
  28.     }  
  29.   }  
8. Save the changes to the database
  1. void ButtonSave_Click(object sender, RoutedEventArgs args) {  
  2.   //save the changes to the database  
  3.   proxy.BeginSaveChanges(SaveChangesOptions.Batch, (asyncResult) =>{  
  4.     try {  
  5.       proxy.EndSaveChanges(asyncResult);  
  6.     }  
  7.     catch(Exception ex) {  
  8.       TextBlockStatus.Text = ex.Message;  
  9.     }  
  10.   },  
  11.   null);  
  12.   //datagrid is not in edit mode anymore  
  13.   inEdit = false;  
  14.   //show the message  
  15.   TextBlockStatus.Text = "Changes Saved to the database";  
9. Currently the Data Contract objects do not support INotifyPropertyChanged or INotifyCollectionChanged so change the Proxy.cs from
  1. [global::System.Data.Services.Common.DataServiceKeyAttribute("UserID")]  
  2. public partial class Users {  
  3.   /// <summary>  
  4.   /// Create a new Users object.  
  5.   /// </summary>  
  6.   /// <param name="userID">Initial value of UserID.</param>  
  7.   public static Users CreateUsers(int userID) {  
  8.     Users users = new Users();  
  9.     users.UserID = userID;  
  10.     return users;  
  11.   }...  
  12.   to[global::System.Data.Services.Common.DataServiceKeyAttribute("UserID")]  
  13.   public partial class Users: System.ComponentModel.INotifyPropertyChanged {  
  14.     public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;  
  15.   
  16.     protected virtual void OnPropertyChanged(string propertyName) {  
  17.       if (PropertyChanged != null) {  
  18.         PropertyChanged(thisnew System.ComponentModel.PropertyChangedEventArgs(propertyName));  
  19.       }  
  20.     }  
  21.     /// <summary>  
  22.     /// Create a new Users object.  
  23.     /// </summary>  
  24.     /// <param name="userID">Initial value of UserID.</param>  
  25.     public static Users CreateUsers(int userID) {  
  26.       Users users = new Users();  
  27.       users.UserID = userID;  
  28.       return users;  
  29.     }... 
That's all. You are done. Build and run the application.
 
To load the data in DataGrid, press the GetData button.  
 
A71.png
 
Select the DataGrid and Press Insert from KeyBoard. A new row will be inserted in the DataGrid. You can type text in this new row and click button Save Data to save the new row in the database.
 
A72.png
 
Press the "Save Data" button, the data will be saved in the database.
 
To delete any row select the row and press the Delete button from KeyBoard, row will be removed from the DataGrid, and to persist the changes in the database click the Save Data button. Similarly to update any column, select the row, update First name or last name, and press the Save Data button.
 

Summary

 
In this article, we learned about Insert, Update, and Delete in Silverlight DataGrid using ADO.NET with example.


Similar Articles