Tuesday, May 6, 2008

Css Style Helper

While working in Asp.net forms always :) We need to change some parameter That is Common to all controls in this page.

Ex1: I need to Get all Page TextBox or Buttons to Apply Css Cascading.
Note1: in Internet Explorer 7 we have problem to apply Hover Cascading.

Whether Ex. or Note1 I Think this Helper will solve it.
Below is a sample method code I use to get a hierarchy of controls on a page:
public static Control[] ControlsPageHierachy(Control root) 
{ 
List<Control> list = new List<Control>(); 
list.Add(root); 
if (root.HasControls()) 
{ 
foreach (Control control in root.Controls) 
{ 
list.AddRange(FlattenHierachy(control)); 
} 
} 
return list.ToArray(); 
} 
ControlsPageHierachy recursively traverses control hierarchy and collects each control it finds on its way to a collection which is finally returned to the caller in a form of an array.

The second step we can use StyletextBox method to apply the onmouseover and onmouseout style of all Textboxes on the page. To do this, a code similar to the one below can be used:
public static void StyletextBox(Page page) 
{ 
Control[] allControls = FlattenHierachy(page); 
foreach (Control control in allControls) 
{ 
TextBox textBox = control as TextBox; 
if (textBox != null) 
{ 
textBox.Attributes.Add("onmouseover", "classChange('TextBoxhover',this);"); 
textBox.Attributes.Add("onmouseout", "classChange('TextBox',this);"); 
} 
} 
To apply style or change some parameter some times you need to add attributes to all controls using Attributes.Add property on event
using also JavaScript function below …
This function will change the CSS class on an object.
function classChange(styleChange,item) 
{ 
item.className = styleChange; 
} 
As you see also this function change Css class on an object I make two styles for our textboxes
.TextBox 
{ 
border-right: lightgrey 1pt solid; 
border-top: lightgrey 1pt solid; 
font-weight: bold; font-size: 8pt; 
border-left: lightgrey 1pt solid; 
width: 160px; 
border-bottom: lightgrey 1pt solid; 
font-family: Tahoma; 
background-color: #f9f9fc; 
color: gray; 
height: 20px; 
} 
 
.TextBoxhover 
{ 
border-right: dimgray 1pt solid; 
border-top: dimgray 1pt solid; 
font-weight: bold; 
font-size: 8pt; 
border-left: dimgray 1pt solid; 
width: 160px; 
border-bottom: dimgray 1pt solid; 
font-family: Tahoma; 
background-color: #eff9fb; 
color: gray; 
height: 20px; 
} 
Now you just need to Call Our Helper Class in your page load event
protected void Page_Load(object sender, System.EventArgs e) 
{ 
StyleHelper.StyleMainControl(this.Page); 
} 
 
Of course all of this is possible thanks to Helpers and Bridges Discoverer 