Blue Theme Orange Theme Green Theme Red Theme
 
ASP.NET Web Hosting – Click Here
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
LeftbarAd
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Silverlight » Insert, Update and Delete in Silverlight DataGrid using ADO.NET

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

In this article will show how to perform CRUD (Create, Retrieve, Update, Delete) operations in Silverlight 2 using ADO.NET Data Services.

Author Rank:
Technologies: ASP.NET 3.5, Silverlight,Visual C# .NET
Total downloads : 526
Total page views :  16885
Rating :
 5/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverlightApplication6.zip
 
ArticleAd
Become a Sponsor



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 Selverlight Datagrid using ADO.NET Data Service.

1. Create a class of the Entities type
               
TestEntities proxy;

2. Create a variable to track if DataGrid is in Edit mode
               
private bool inEdit;

3. Create Page_Loaded event to initailize the ADO.NET Data Service
               
void Page_Loaded(object sender, RoutedEventArgs e)

        {

            proxy = new TestEntities(new Uri("WebDataService.svc", UriKind.Relative));

        }

4. Create Events for the DataGrid
               
<my:DataGrid x:Name="dataGrid" Margin="10" AutoGenerateColumns="True"

                     AutoGeneratingColumn="OnGeneratedColumn" BeginningEdit="dataGrid_BeginningEdit" CommittingEdit="dataGrid_CommittingEdit" CancelingEdit="dataGrid_CancelingEdit" 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
               
private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)

        {

            inEdit = true;

        }
      private void dataGrid_CancelingEdit(object sender, DataGridEndingEditEventArgs e)

        {

            inEdit = false;

        }
      private void dataGrid_CommittingEdit(object sender, DataGridEndingEditEventArgs e)

        {

            //Attach the object to the context.

            try

            {

                proxy.AttachTo("Users", dataGrid.SelectedItem);

            }

            catch

            {

            }           

            proxy.UpdateObject(e.Row.DataContext);

        }

6. Create a ObservableCollection
               
/// <summary>

      /// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

      /// </summary>

      ObservableCollection<Users> BoundData

      {

            get

            {

                return (dataGrid.ItemsSource as ObservableCollection<Users>);

            }

      }

 

7. KeyDown Event of the DataGrid to Insert, Update and Delete rows
               
private void dataGrid_KeyDown(object sender, KeyEventArgs e)

        {

            if (!inEdit)

            {

                TextBlockStatus.Text = "";

                if (e.Key == Key.Delete)

                {

                    if (dataGrid.SelectedItem != null)

                    {

                        //Attach the object to the context.

                        try

                        {

                            proxy.AttachTo("Users", dataGrid.SelectedItem);

                        }

                        catch (Exception ex)

                        {

                            TextBlockStatus.Text = ex.Message;

                        }

                        proxy.DeleteObject(dataGrid.SelectedItem);

                        // Remove from the bound collection, disappears from DataGrid.

                        BoundData.Remove(dataGrid.SelectedItem as Users);

                    }

                }

                else if (e.Key == Key.Insert)

                {

                    Users u = new Users() { FirstName = "", LastName = "" };

                    int index = BoundData.IndexOf(dataGrid.SelectedItem as Users);

                    BoundData.Insert(index, u);

                    dataGrid.SelectedIndex = index;

                    dataGrid.BeginEdit();

                    proxy.AddObject("Users", u);

                }

            }

        }

8. Save the changes to the database
               
void ButtonSave_Click(object sender, RoutedEventArgs args)

        {

            //save the changes to the database

            proxy.BeginSaveChanges(SaveChangesOptions.Batch, (asyncResult) =>

            {

                try

                {

                    proxy.EndSaveChanges(asyncResult);

                }

                catch (Exception ex)

                {

                    TextBlockStatus.Text = ex.Message;

                }

            }, null);

            //datagrid is not in edit mode anymore

            inEdit = false;

            //show the message

            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
               
[global::System.Data.Services.Common.DataServiceKeyAttribute("UserID")]

    public partial class Users

    {

        /// <summary>

        /// Create a new Users object.

        /// </summary>

        /// <param name="userID">Initial value of UserID.</param>

        public static Users CreateUsers(int userID)

        {

            Users users = new Users();

            users.UserID = userID;

            return users;

        }
      . . .
      to
      [global::System.Data.Services.Common.DataServiceKeyAttribute("UserID")]

    public partial class Users : System.ComponentModel.INotifyPropertyChanged

      {

            public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

 

            protected virtual void OnPropertyChanged(string propertyName)

            {

                  if (PropertyChanged != null)

                  {

                        PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));

                  }

            }

        /// <summary>

        /// Create a new Users object.

        /// </summary>

        /// <param name="userID">Initial value of UserID.</param>

        public static Users CreateUsers(int userID)

        {

            Users users = new Users();

            users.UserID = userID;

            return users;

        }
      . . .

 

That's all. You are done. Build and run the application.

To load the data in DataGrid, press GetData button.  

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.


Press "Save Data" button, the data will be saved in the database

To delete any row select the row and press Delete button from KeyBoard, row will be removed from the DataGrid and to persist the changes in database click the Save Data button. Silimarly to update any column, select the row , update First name or last name and press Save Data button.

 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Nipun Tomar
Nipun has 5 years working experience in .NET technologies. He holds Bachelor's and Master's degree in Computer Science. Currently working on ASP.NET 2.0/3.5, VB.NET, C#.NET, AJAX, SQL Server 2005, WPF, WCF and Silverlight.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverlightApplication6.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
No parameterless Constructor defined for this objectumar10/13/2008
when i implemented previous and this article i got this exception "No parameterless Constructor defined for this object" on data binding with datagrid.itemsource. Can u tell me plz y is that so.kindly email me the solution.
Reply | Email | Delete | Modify | 
about CommittingEdit and CancelingEdit eventsJiang11/3/2008
your code is helped me to much. Now, I have some question, I can't find CommittingEdit and CancelingEdit events in my DataGrid. Can you help me , thanks a lot
Reply | Email | Delete | Modify | 
Insert, Update and Delete are not working.Dipsa1/19/2009
This article is very useful to me. I have used above code to prepare a CRUD operation using VB.Net. Project build successfully. but when i click 'Insert' nothing happens, when i update row and click 'Save' button DB row not updating. Please help me. can you please provide same example in vb.net? Thanks a lot.
Reply | Email | Delete | Modify | 
how to use with SL2 RTMAndrus1/20/2009
Trying to compile this sample in SL2 RTM causes warnings Warning 1 The property 'CommittingEdit' does not exist on the type 'DataGrid' in the XML namespace 'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data'. C:\ssleditingingrid\SilverlightApplication6\SilverlightApplication6\Page.xaml 13 22 SilverlightApplication6 Warning 2 The property 'CancelingEdit' does not exist on the type 'DataGrid' in the XML namespace 'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data'. C:\ssleditingingrid\SilverlightApplication6\SilverlightApplication6\Page.xaml 13 63 SilverlightApplication6 Sample saves changes in CommittingEdit event. Since this event does not exist in RTM, this code cannot used to save changes: moving to other row is not dedected by code. How to fix ? Andrus.
Reply | Email | Delete | Modify | 
CommittingEdit="dataGrid_CommittingEdit" Not WorkingJoseph Britto6/4/2009
I can't get  CommittingEdit="dataGrid_CommittingEdit"  in .xaml page.
Reply | Email | Delete | Modify | 
 
 
Re: CommittingEdit="dataGrid_CommittingEdit" Not WorkingNipun6/11/2009
use dataGrid_RowEditEnding instead.

private void dataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)

        {

            //Attach the Link object to the context.

            try

            {

                proxy.AttachTo("Users", dataGrid.SelectedItem);

            }

            catch

            {

            }

            proxy.UpdateObject(e.Row.DataContext);

        }


Reply | Email | Delete | Modify | 
ProblemJai7/1/2009
Hi,
Its a good sample :)

However, I am getting two errors when I build.

Error 1 'System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs' does not contain a definition for 'Property' and no extension method 'Property' accepting a first argument of type 'System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs' could be found (are you missing a using directive or an assembly reference?) D:\Tutorials\Silver Light Samples\silverLightSimpleGrid\SilverlightApplication6\SilverlightApplication6\Page.xaml.cs 152 19 SilverlightApplication6

Error 2 Could not load file or assembly 'Microsoft.Data.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified. D:\Tutorials\Silver Light Samples\silverLightSimpleGrid\SilverlightApplication6\SilverlightApplication6Web\web.config 44 

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved