Friday, 13 July 2012

Loop through all controls in a page in asp.net

Loop through all controls on a page asp.net using following code:-
(Very helpful when masterpage is used in website)

ArrayList ar = new ArrayList();
Control[] ControlArray = GetControls(pagename.Controls, ref ar);
if (permission == "False")
{
for (int i = 0; i < ControlArray.Length; i++)
{
//Make all controls Read only
ReadOnlyControls(ControlArray[i]);
}
}


public static Control[] GetControls(ControlCollection parent, ref ArrayList controls)
{
foreach (Control c in parent)
{
controls.Add(c);

if (c.Controls.Count > 0)
{
GetControls(c.Controls, ref controls);
}
}

return (Control[])controls.ToArray(typeof(Control));
}

public static void ReadOnlyControls(Control control)

{
if (control is WebControl)
{
WebControl webControl = (WebControl)control;
string typeName = webControl.GetType().Name;
switch (typeName)
{
case "LinkButton":
case "GridViewLinkButton":
case "TextBox":
case "RadioButton":
case "CheckBox":
//SwapControl(webControl, GetPropertyValue(webControl, "Text"));
webControl.Enabled = false;
break;
case "Button":
webControl.Visible = false;
break;
case "RadioButtonList":
case "DropDownList":
//ListControl list = (ListControl)webControl;
//string text = "";
//if (list.SelectedItem != null)
//{
// text = list.SelectedItem.Text;
//}
//SwapControl(webControl, text);
webControl.Enabled = false;
break;
case "ImageButton":
webControl.Visible = false;
break;
case "GridView":
GridView grid = (GridView)webControl;
foreach (GridViewRow item in grid.Rows)
{
foreach (Control itemControl in item.Controls)
{
ReadOnlyControls(itemControl);
}
}
break;
default:
//Response.Write(webControl.GetType().FullName + "
");

break;
}
}
for (int n = 0; n <>
{
Control childControl = control.Controls[n];
ReadOnlyControls(childControl);
}
}

public static void SwapControl(Control oldControl, Control newControl)
{
Control parent = oldControl.Parent;
int index = parent.Controls.IndexOf(oldControl);
parent.Controls.RemoveAt(index);
parent.Controls.AddAt(index, newControl);
}

public static void SwapControl(Control oldControl, string text)
{
SwapControl(oldControl, new LiteralControl(text));
}

public static string GetPropertyValue(Control control, string propertyName)
{
Type type = control.GetType();
object o = type.InvokeMember(propertyName, BindingFlags.Instance |

BindingFlags.GetProperty | BindingFlags.Public, null, control, null);
return Convert.ToString(o);
}

No comments:

Post a Comment

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...