Example Lock Dataset in C#

This is an example of how to lock your database or prevent data in the dataset to changed (read-only dataset).

In a large web application, you may have a reference table in the database, and the application no need to read on the reference table every time the application needs to get a 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 / read-only.

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);
}
}

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example