Howto: Get, Update, Delete in Silverlight DataGrid using WCF Service

Bollywood News, Movie Reviews, Watch new released hindi movies  and TV Episodes online for free.

If you want to know the features of Silverlight 3 datagrid and how to setup datagrid control in Silverlight application, here is my previous link.

Here I will walk through

  • how you can get data from SQL Server database and bind it to Silverlight Datagrid
  • how you can update, delete records in Silverlight 3 DataGrid using WCF Service

1)  Create Silverlight Application and Setup DataGrid

Here is my previous link that walks you through how you can do that.

2) Get, Update and Delete in Silverlight DataGrid using WCF Service

There is no System.Data namespace available in Silverlight application so you can’t connect to ADO.NET enabled database to get the data and bind directly to Silverlight DataGrid.  Since we are missing System.Data namespace, DataSet / DataTable that mainly used by developer to bind data also NOT available.

But there are three different approach available to bind data centric application in Silverlight now.  Here is the link that explains those three diiferent approach. Here I will create WCF Service one of three approach available.

This WCF Service will be main communication point from Silverlight Application.  To update/get data from database, we will LINQ to SQL class.  To know more about LINQ to SQL, you can refer MSDN article here.

Adding LINQ to SQL Class

To add LINQ to SQL Class file, right click on silverlight web project and add new item and choose LINQ to SQL Classes template.

Once you click on Add it will open DataClasses.dbml (object relational designer) file.  Now click on “Server Explorer” link.  It will open “Server Explorer” window where you can establish your sql server database connection. For our sample application, I have created pub database and within that database I have created Members table.  To create a supported database and table, I have included SQL Script in the source so run the sql script before moving forward because we need to have those database and table created while working with LINQ to SQL class.

Now establish the pub database connection from “Server Explorer” window.  Now drag and drop Members table to DataClasses.dbml file.

It will generate Members LINQ Class corresponding to Members table we have in pub database. By default this class in not serializable and we will pass list of members object to silverlight application through WCF Service, so we need that class to be serializable.   To do that, click on empty area on DataClasses.dbml file and right click -> properties, it will open property window for entire class.  You will see serialization mode property and change it to Unidirectional.

Adding WCF Service

To add WCF Service, right click on Silverlight web project and click on Add New Item and choose WCF Service template.

It will create IDataService.cs service contract and DataService.svc WCF Service file.  If you are not familiar with WCF Service, you can find out more about WCF here.

Now open IDataService.cs file.  There will be dummy contract “DoWork()” created in service contract file.  Replace that DoWork() contract with the contract method “GetMembers” that we need to get the list of members object and also change the return type void to List<Member>.  When you try to change return type, you will see Member class in intellisense window that’s LINQ to SQL Class created and associated to Members table in pub database.

So we changed the service contract “DoWork()” to “GetMembers()”.   Now open DataService.svc.cs file.  You will see that DataService class in that file implements IDataService service contract that we just modified.  Since we have modified dummy contract to the actual contract that we need, remove DoWork method from DataService.svc.cs file. We need to implement the “GetMembers()” service contract here.  To do that, click on interface class IDataService name,  you will the smart tag poped up so click on “Implement interface IDataService” it will create implementation of “GetMembers()” for you.(Easy to do that ah…. smart way…  right??  I like that smart tag because I hate to type )  Now put the actual code in that method to get list of members using DataClassContext.

So we got GetMembers method ready to use.   Now can you create UpdateMember method the same way we created GetMembers method??  It’s very straight forward.

DataService.svc.cs (updated on April 7, 2010 to fix bug in UpdateMember method)

So we have now ready GetMembers and UpdateMembers method to use.  Only one thing is left to change for WCF service is that HttpBinding in web.config.  WCF uses wsHttpBinding by default and since Silverlight only supports basic httpbinding so change we need to change binding in web.config.

Now build the solution to make sure all above steps went well.

Adding Reference in Silverlight Class Project

Right click on Silverlight Class library -> Add Service Reference.  It will open Add Service Reference window now click on Discover button it will search for WCF Service within a solution and will list the service we created so far.

Click on the service that found and expand that tree you will see the GetMembers and UpdateMember operation in right box. Click Ok to add reference of those operations in Silverlight class library project.

Now it’s time to call those service operation (GetMembers and UpdateMember) from silverlight code behind file.  To do so, open MainPage.xaml.cs file.  Please make sure you have installed Silverlight 3.0 tools for Visual Studio 2008 SP1 the reason why I am saying that you will have BeginningEdit and RowEditEnded event in Silverlight 3.0.  You won’t find RowEditEnded that is very useful event but was missing in Silverlight 2.0.

Now wire up BeginningEdit and RowEditEnded event of Silverlight datagrid in Code behind class constructor.

So now we have BeginningEdit and RowEditEnded event is ready to use.

Binding data to datagrid

Now let’s first bind the Silverlight datagrid.  Since Silverlight application is running in browser, only way to call web service is asynchronously.  To do so,  first create a web service client object and then wire up  GetMembersCompleted event that will be called when asynchronous GetMembers webservice call will be completed.

Now hit F5 to run the application and see what you got so far.  You will see the data from Members table of pub database bound to datagrid.  Here is the result

Updating row in Silverlight DataGrid

Now let’s add logic in dgSilverlight_RowEditEnded method that wrapped up dgSilverligh.RowEditEnded event to handle update logic.  When you click on any column of datagrid, it will turn into editable textbox so you can modify the value.  Once you change focus out of that row (yes out of the row not just column),  dgSilverlight_RowEditEnded method will be fired and you can retrieve updated row value using e.Row.DataContext and cast it to Member LINQ to SQL Class.   Then you can call UpdateMember service call asynchronously passing updated Member object.

Here it is how you can code that.

Now run the application and try updating any row.  Bingo….  we are done with update.

Deleting row in Silverlight DataGrid

Any idea how you can accomplish delete operation in DataGrid???  I will give you guide how you can do that.  You need to wire up OnKeyDown event and you can check if the delete key press and any datagrid item is selected, then you can delete that selected datagrid row.  Can you do it yourself??   Try our self first and if you are running into any issue, here is the complete source code that will help you understanding.  Here is live demo page.

Updated on 1/1/2011:

Here is my latest article where you can download latest Silverlight 4  DataGrid Example with Add, Update and Delete.  If you have latest version of visual studio and silverlight installed, I would recommend you to go to my latest article to download latest code.

If you are interested to know about Silverlight PivotViewer control, check this my other article for step by step guide how to create Silverlight PivotViewer application.

Any question or problem running sample code please leave your comment here.  If this post really helps you, please click the Google +1 button to show it really helps you save your time.

Posted in Microsoft Technology Tagged with:
50 comments on “Howto: Get, Update, Delete in Silverlight DataGrid using WCF Service
  1. Harish says:

    Nice post.Very helpful

  2. DC says:

    This does not work, in the dataservice, how can you be doing mem.Equals(objMem), looking for the updated record in the database?

    and then assigning that line to var member, and then member = objMem. What do you do with member then? db.submitChanges() does not reflect any changes??

    Is that correct, as I cannot get update to work.

    Thanks

  3. jignesh says:

    Hi,
    i have go throw this example and create one sample project and also download your code.These both works but does not affect database.Can you explain why this happened? Or I have missed some code?

  4. Shailesh says:

    @jignesh,@DC

    I agree on your comment that there is a bug in the code I posted.

    here is the updated “UpdateMember” method

    public bool UpdateMember(Member objMem)
    {

    DataClassesDataContext db = new DataClassesDataContext();
    db.Members.Attach(objMem,true);
    db.SubmitChanges();

    return true;

    }

  5. Ryan says:

    Shailesh,

    I’m a new comer to the LINQ stuff and your comment on april 6th left me confused.

    If you could take the 5 minutes and fully update what the UpdateMember function would look like that would help a lot. I don’t know what can be droppend when you talk about simply attaching the objmem to datacontext and submit the changes…. I totally get lost unless I see this presented in simple code the first time….

    I have been able to do so much with what you have started me with…. Grouping and the like I was able to figure out, but this I can’t and I need your help.

  6. Shailesh says:

    @Ryan I have updated my comment and put the modified version of “UpdateMember” method.

    I have also changed the sourcecode so if you get latest sourcecode again you should be fine.

    FYI db.Members.Attach(objMem,true) was throwing an error “An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy”. db.Members.Attach(objMem,true) is little bit tricky in N-tier application because objMem is detached from original DataContext and DataContext is not able to track that object changes that’s why it was throwing the error I just mentioned. In order to make it work I have added timestamp column in members table.

    Here is the good article about LINQ to SQL in N-Tier application.

  7. Ryan says:

    You were correct, adding a Timestamp fixed the issue… I just added a column called timestamp and it fixed the issue. May I ask why this seems to work??

    Is there any other way around it I’m just curious…. Your tutorial was great and getting this to work was great, but just wondered if there is a different way of editing data in LINQ to SQL… How about a tutorial about adding a new record???

  8. Shailesh says:

    @Ryan,

    If you are not using WCF or you modify the object within a DataContext scope, that will work without any problem.

    DataClassesDataContext db = new DataClassesDataContext();
    var member = from m in db.Members
    where m.Member_id = 1
    select m;

    member.FirstName = “NameChanged”;

    db.SubmitChanges();

    this will work without any problem because member object is within a DataContext scope.

    Our WCF example, member object is detached from datacontext(DataContext object created in Get and Update method so two different instance of DataContext) so to make it work we need to have timestamp. If you are wondering about other alternatives you can refer this article.

    I am bit busy now a days but I will post tutorial about adding a new record shortly.

  9. Louis says:

    Hello Sailesh,

    Thank you for your very nice demo.

    BTW, it’s still not working. I execute your SQL Script and run your demo and I got an error.

    At this line db.SubmitChanges() I got this error Row not found or changed.

    Thank you for your time.

  10. Srikanth says:

    Shailesh or Ryan,
    Why do we need to add another column to the table.
    Also could you please send me the code to Add a row, Delete a row and Updating a row (while updating the DB with every action). Am using WCF service to bring the data into the grid.
    This is very urgent, i have a final submission tomorrow.

    Thanks for your time.

  11. Ryan says:

    Shailesh,

    You have been so immensly helpful. I know you are busy, but I have tried everything I can to work with adding new records to the table and I can’t do it. (I am ignoring using the data grid to add records, but if it can be done that would be great), but I’m just trying to add new records and refresh the datagrid to see them and it never works…

    This is so important that I figure this out….

    -R

  12. Ryan says:

    I figured it out Shailesh,

    public bool updateBlankUser()
    {
    //UserDS db = new UserDS();
    UserTableClassesDataContext db = new UserTableClassesDataContext();
    User newUser = new User();
    User blankUser = new User();
    newUser.FirstName = “Blank”;
    newUser.Maintenance = true;
    newUser.Supervisor = false;
    newUser.UserName = “NeedToEdit”;
    newUser.IsAdministrator = true;
    newUser.Active = 1;
    newUser.LogPath = “c:\”;
    newUser.RelativePath = false;
    newUser.ReportsFolder = “c:\”;
    newUser.DaysToKeep = 1000;
    newUser.Hidden = false;
    newUser.IsApproved = true;
    newUser.IsExpired = false;
    newUser.PersistOrgSettings = true;

    db.Users.InsertOnSubmit(newUser);

    //Note here to ALL DEVELOPERS, make sure you take care of your none null fields like I did above, but make sure you deal with ALL OF YOUR DATETIME fields, null or not and set them to a valid value. I put a breakpoint on the exception and found thats what the problem was….

    Now it works.

    try
    {
    db.SubmitChanges();
    }
    catch (Exception ex)
    {
    return false;
    }
    return true;
    }

  13. Shailesh says:

    @Ryan
    Implementation of delete operation was left up to reader. I had provided the information how you can delete the rows.

    The code you have provided for inserting new record, why do you need to insert default values? You should have UI for inserting new member and fill up member object and pass that object using WCF like I did for update.

  14. Shailesh says:

    @Srikanth @Ryan,

    here is the WCF code to delete object.

    public bool DeleteMember(Member objMem)
    {
    DataClassesDataContext db = new DataClassesDataContext();

    var mem = db.Members.First(m => m.Member_id == objMem.Member_id);
    db.Members.DeleteOnSubmit(mem);
    db.SubmitChanges();

    return true;
    }

    I will update this post and source code to include delete operation since I am getting lot of requests for that. I probably do that over this weekend.

  15. Ryan says:

    Shailesh,

    I declared all the not null values because I was just running a test to see what I needed to have entered bare minimum to have a new record entered. I just did it all by code to test it out… didn’t want to waste time on a UI that would be wasted, I just wanted to quickly add new records and it works great!..

    The only thing I stress is that ALL DATETIME values must either be set to something valid, or explicitly set to null.

    The fields listed are only a small number of the fields in the table…. the ones I have shown here are the not null fields…. The other fields I didn’t care about in this test… I just wanted to get the bare minimum entered so that everytime I press enter new user… one gets generated…

  16. Shailesh says:

    @Louis

    I think you have to update service reference in silverlight project because I have updated WCF service to make it work.

  17. Shailesh says:

    Guys,

    I have updated source code to include delete operation in silverlight datagrid.

  18. Durga Prasad says:

    Sailesh ..Thank you for the remarakable article!!.

    Can u please let us know the steps to update the table only on confirmation from user.Instead of updating things in
    dgSilverlight_RowEditEnded ….can we think of a ‘Save Button’,which will seek confiramtion from the user before updating recrods..

  19. Durga Prasad says:

    Sailesh,
    I gave a shot and did it this way.Please suggest there is better way to do..

    //Declare a variable in the name space in code behind
    public List listMembers;

    //Add this line in public MainPage()
    listMembers = new List();

    //Change this function , add all the rows edited into a List
    void dgSilverlight_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
    {
    listMembers.Add(e.Row.DataContext as ServiceReference.Member);

    }

    //Update all edited records if user clicks on save button
    private void Save_Clicked(object sender, RoutedEventArgs e)
    {

    ServiceReference.DataServiceClient webService = new DataServiceClient();
    webService.UpdateMemberCompleted += new EventHandler(UpdateMemberCompleted);

    for(int i=0;i<listMembers.Count;i++)
    webService.UpdateMemberAsync(listMembers[i]);

    }

  20. Shailesh says:

    @Durga Prasad

    One thing you can approve in your approach to update is that instead of loop through list and call update method for each item, you can pass entire list to UpdateMember web method and update the rows at one shot.

  21. Durga Prasad says:

    Please add a code snippet to update at one go.I just learning
    WCF,so not sure how I do that.

  22. Piseth says:

    Hi, I tried with your new code.
    but it seem doesn’t work.
    I can’t add new row, I can edit, but it doesn’t save.
    I can delete by select the row and press delete key.

    So How can I add new data in to the new rows, and edit it and save?

    Please !!!

  23. Shailesh says:

    @Piseth

    The code I have posted here is to Get,Edit, Delete record in Silverlight DataGrid. You have mentioned that you can’t edit the record. What error are you getting?

  24. Lalith says:

    Hello,
    I am new to webservices in .net. I have tried this code and works perfectly fine. But I am constrained not to use Linq. So inside webservice I just used same old code with SQLClient and datareader to do the database operations. However I cannot return datareader from a webservice it needs to be serializable. So I tried to make arraylist of each row. But the datagrid.Itemsource when assigned to this array list just shows the count of columns in each row instead of the row data. What should I do here? Instead of Arraylist is there any collection object I need to use? Any tips would be a great help.

    Regards,
    Lalith.

  25. Manish says:

    Hi,
    Can any one help me to make some application using SQL Server,WCF and ASP.Net3.5.
    function is subscribe the data from Sql Database and auto refresh with out using Pooling.

    Thanks

  26. Shailesh says:

    @Manish,
    Sure. Send me your contact info.

  27. Shailesh says:

    @Lallith,
    There are couple options
    1) Return DataSet and bind it to datagrid
    2) Build list of custom objects and return that
    3) You can also bind arraylist to datagrid. Refer my other article about Howto: Bind array to repeater control

  28. Silvernut says:

    Im creating a Silverlight application that will update/delete and insert new rows, it started fine, and i can see data from my customDB in the datagrid, but i can’t update, i have downloaded your source code and your app works just fine, but mine doesnt,
    al though i have followed your article, im been getting this error:

    The remote server returned an error: NotFound:
    System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. —> System.Net.WebException: The remote server returned an error: NotFound. —> System.Net.WebException: The remote server returned an error: NotFound.

    i have no problem selecting data but update is not working,
    help?

  29. Shailesh says:

    @Silvernut,
    It seems like that WCF/Webservice url is wrong or your silverlight application is not able to connect to that URL.

  30. Silvernut says:

    Thanks for the quick answer i really apreciate your help,
    In my projectsolution i have 3 projects,
    1 Silverlight project, 1 Webproject (that came when i choose Silverlight project + Webapp)
    and The WCFService.

    According to my Service project(by debug instance)the url, including port are ok, i can see it in the ServiceReferences.ClientConfig,
    and if they weren’t i would be getting the error when i try to launch the application (which i don’t)

    I have two web.config files one in the webproject and one in the service project, (i saw you only had one in your solution) do i need to apply changes to web.config? does it matter?

    Best Regards
    /Silvernut

  31. Rohit Rathod says:

    Hi,

    I have an example of bind datagrid using XML and using database with web services.

    But can you help me to bind datagrid using database WITHOUT web services ?

    Thanks and Regards,
    Rohit

  32. Shailesh says:

    @Rohit Rathod,

    Silverlight application is a browser based application that can be executed on client machine. Having said that if Silverlight application need any kind of data from server, it may need to request through Web Service/WCF. So to answer to your question is NO you can’t bind silverlight datagrid WTHOUT Web Service/WCF.

    If you want to understand Silverlight application architecture or how browser render/execute silverlight application, you can refer this article.

  33. Dan says:

    Hi,

    Excellent guide.. but I must be doing something wrong. I get the error:

    The name ‘webService_GetMembersCompleted’ does not exist in the current context.

    Do you know why this might be? Any help would be much appreciated!

    Thanks

  34. Hi Shailesh
    Your blog for Get,Update,delete in silverlight Datagrid using WCF is very help full to me.It’s working in Silverlight Application.But when i hosting in the my web application that time only seen the empty grid dot display data.can you please tell me how to hosting this application in Existing web application.It;s my pleasure you tell me.

    Thanks
    Somanath

  35. Mandeep says:

    nice post,helping me to solve my problem

  36. Zack says:

    Thanks for the post. This is exactly what I needed to get started. Tremendous help!

  37. vinay says:

    good post. thanks

  38. Xanky says:

    Hi Sailesh

    Very nice example

    how to join 2 tables and convert into to list to return it. i have tried adding table to your sample say order which has member id now added another datagrid and showing all orders which member has now want to show the member last name it and it is not allowing. do you have sample with 2 tables and joining with linq ?

  39. tarun says:

    hi sir ,
    thanks for guiding as a invisible guru,and that is very helpful,
    i’ve some doubts regarding silverlight
    1)how to deploy a silverlight application?
    2)what are dependancy properties in silverlight?
    3)how to achive statemanagent technique’s in asp.net in silverloght?
    i saw some articles as answers to my q’s but i need some thing which is very clear like this
    thanks in advance.tarun

  40. doremifasolati says:

    This is exactly what I was thinking and i’m looking for more at google

  41. lizarazou says:

    I follow this tutorial but the update of the database don’t work , please help me how to correct it

  42. Richard says:

    Having a issue on insert as a whole row not editing. For some reason its only grabbing the last item in last column and setting it for the first column value if I fill all of them out. If I only fill out one or two and the rest are empty it sets that first item in column to nothing. Very strange….

  43. ArishSimbac says:

    Hi – I am certainly happy to discover this. Good job!

  44. chitra says:

    hi shailesh,
    thanks for the wonderful article , you solved a big problem of mine.actually i am new to silverlight. shailesh is there any way that i can create excel like grid , actually my client needs a bulk entry sheet(batch entry), which should be collectively submitted to database

  45. robin says:

    very nice post..

  46. Hamdy says:

    Really very useful i was struggle to find that ,but small thing is there in linq dataclasses we should modify the column update check properties to NEVER then every thing will work perfect thanks again and again

  47. #harris29[TIAGCTGTVGIV] says:

    Hi – I am really glad to find this. cool job!

  48. NhatNguyen says:

    private void LoadButton()
    {
    int x = 30;
    int y = 12;
    int j = 0;
    var q = from a in data.Tables
    select a;
    var count = q.Count();
    for (var i = 0; i <= count; i++)
    {
    j = i + 1;
    Button bt = new Button();
    bt.Size = new Size(200, 74);
    bt.Top = x;
    bt.Left = y;

    bt.Name = q.First().ID.ToString(); <- wrong
    bt.Text = q.First().Name.ToString(); <- wrong
    x += 173;
    if (j % 6 == 0)
    {
    x = 30;
    y += 84;
    }
    pnButton.Controls.Add(bt);
    }

    }
    select data of row in database but it erow, can you fix it for me,Thanks

  49. Brian says:

    This post is really helpful.

  50. Lucky Ahuja says:

    Hi Shailesh,

    Could not found the Complete Source code as the link says that the page has been removed . cud u please provide me the link for the same.

    Thanks

3 Pings/Trackbacks for "Howto: Get, Update, Delete in Silverlight DataGrid using WCF Service"
  1. […] my previous article , I have explain in details how you can bind data, update and delete record in silverlight data […]

  2. Howto: Get, Update, Delete in Silverlight DataGrid using WCF ……

    […]Silverlight 4 DataGrid Example with Add Edit Delete using Linq WCF | Broken Code February 11th, 2011 7:23 pm. […] my previous article , I have explain in details how you can bind data, update and delete record in silverlight data [. …[…]…

  3. […] will show you how you can get, delete, update in Silverlight datagrid using ADO.NET Data Service(WCF Service) in my next […]

Ads