Saturday, March 24, 2012

C# - Change attributes of all controls in ASP page

Sometime it requires disabling all controls in the web page using code-behind. Can use following logic to disable all controls in the page without go through each and every control.
private void MakePageControlsReadOnly(Control pageControl)
{
foreach (Control childControl in pageControl.Controls)
{
if (childControl.GetType() == typeof(Control type you want to disable))
{
((Control type you want to disable)childControl).Enabled = false;
}
if (childControl.Controls.Count > 0)
{
MakePageControlsReadOnly(childControl);
}
}
}

This not only for page level this pageControl variable can be a control which contains child controls like table contains link buttons. This generic method can change to change any attribute of the control rather than enable/disable.

Change visibility of child control.

((Control type you want to disable)childControl).Visible = false;

Adding attributes for all link buttons in the table cell.

((TableCell)childControl).Attributes.Add("OnClick", "return false;");


This control type can be extend to other control types like Rad Controls.

((RadGrid)childControl).Attributes.Add("OnClick", "return false;");

Complete example

private void MakePageControlsReadOnly(Control pageControl)
{
foreach (Control childControl in pageControl.Controls)
{
if (childControl.GetType() == typeof(TextBox))
{
((TextBox)childControl).Enabled = false;
}
else if (childControl.GetType() == typeof(CheckBox))
{
((CheckBox)childControl).Enabled = false;
}
else if (childControl.GetType() == typeof(DropDownList))
{
((DropDownList)childControl).Enabled = false;
}
else if (childControl.GetType() == typeof(RadDatePicker))
{
((RadDatePicker)childControl).Enabled = false;
}
else if (childControl.GetType() == typeof(Button))
{
((Button)childControl).Enabled = false;
}
else if (ChildControlsCreated.GetType() == typeof(RadTimePicker))
{
((RadTimePicker)childControl).Enabled = false;
}
else if (ChildControlsCreated.GetType() == typeof(LinkButton))
{
((LinkButton)childControl).Enabled = false;
}
else if ((childControl).GetType() == typeof(TableCell))
{
((TableCell)childControl).Attributes.Add("OnClick", "return false;");
}
else if ((childControl).GetType() == typeof(RadGrid))
{
((RadGrid)childControl).Attributes.Add("OnClick", "return false;");
}

if (childControl.Controls.Count > 0)
{
MakePageControlsReadOnly(childControl);
}
}
}

How invoke this method in page level.

MakePageControlsReadOnly ((Control)this);