Friday 2 October 2015

Example Lock Dataset in C#

Leave a Comment
This is example how to lock your database or prevent data in dataset to changed (read only dataset).

In large web application, you may have reference table in database, and the application no need to read on the reference table every time the application need to get reference. You can store the reference table in cache memory. But you afraid that the data might accidentally  changed by your code. This is the way to make your dataset lock / readonly.

Lock Dataset method

  /// <summary>   
     /// Makes the given DataSet read-only   
     /// </summary>   
     /// <param name="ds">DataSet</param>   
     public static void LockDataSet(DataSet ds)  
     {  
       // Do not lock null   
       if (ds == null)  
       {  
         return;  
       }  
       EventHandler locked = (sender, e) =>  
       {  
         string msg = String.Format("DataSet '{0}' cannot be modified, it is read-only.", ds.DataSetName);  
         throw new InvalidOperationException(msg);  
       };  
       // Prevent table modification   
       foreach (DataTable t in ds.Tables)  
       {  
         t.RowChanging += new DataRowChangeEventHandler(locked);  
         t.RowDeleted += new DataRowChangeEventHandler(locked);  
         t.ColumnChanging += new DataColumnChangeEventHandler(locked);  
         t.TableClearing += new DataTableClearEventHandler(locked);  
         t.TableNewRow += new DataTableNewRowEventHandler(locked);  
       }        
     }   


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.