Wednesday, 9 July 2008

Setting all Columns Read Only value

There are occasion where we may want to set all read only properties of our data columns to false or true. When we instantiate our dataset using our Dal.GetSchema() method it can set certain fields to ReadOnly, when we actually want to write to them at the front end. Here's a function to change this.

///
/// Set all columns property readonly to false
///

private void SetReadOnlyFalse(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataColumn dc in dt.Columns)
dc.ReadOnly = false;
}
}


Note that we can easily change the code to make the entire Dataset readonly.

///
/// Set all columns property readonly to true
///

private void SetReadOnlyTrue(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataColumn dc in dt.Columns)
dc.ReadOnly = true;
}
}

Or we could pass a parameter to our function to allow us to use one fucntion for both operations.

///
/// Set all columns property readonly to the boolean blReadOnly
///

private void SetReadOnly(DataSet ds, bool blReadOnly)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataColumn dc in dt.Columns)
dc.ReadOnly = blReadOnly;
}
}


Please note that the code for the Dal.GetSchema just returns an empty dataset structure for a set of table from our SQL server database. The code discussed here will work for any dataset in .Net

No comments:

Free Hit Counter