Skip to content

Instantly share code, notes, and snippets.

@aromig
Created July 13, 2018 17:32
Show Gist options
  • Save aromig/ede08f120ecbed7c9734fa591eaac20d to your computer and use it in GitHub Desktop.
Save aromig/ede08f120ecbed7c9734fa591eaac20d to your computer and use it in GitHub Desktop.
C# Grabbing a Control from a UserControl that's somewhere in a MasterPage
/* Function defined in a class
Used to grab a control that's inside a UserControl
on a page that uses a MasterPage
App_Code\Globals.cs */
public static Control GetUCControl(string UserCtl, string Ctl)
{
Page page = (Page)HttpContext.Current.CurrentHandler;
MasterPage master = page.Master;
// The UserControl is in the ContentPlaceHolder
ContentPlaceHolder cph = (ContentPlaceHolder)master.FindControl("ContentplaceholderID");
// Using a custom method to dig through the control hierarchy
UserControl user_ctrl = (UserControl)FindControlRecursive(cph, UserCtl);
Control ctrl = user_ctrl.FindControl(Ctl);
return ctrl;
}
// Since it returns as a Control, need to cast it as the Control type expected
// Usage from page:
Label label_control = Globals.GetUCControl("UserControlID", "lblControlID") as Label;
// Now can access the control's properties
label_control.Text = "Wicked Sick 💥";
// Digs through the control hierarchy starting at a root control
// stopping when the ID matches
private static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
foreach (Control control in root.Controls)
{
Control child = FindControlRecursive(control, id);
if (child != null)
return child;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment