public void FindControlRecursive() { // Type var @this = new Control(); @this.Controls.Add(new Control {ID = "Fizz"}); @this.Controls[0].Controls.Add(new Literal {ID = "Buzz"}); // Examples Control value1 = @this.FindControlRecursive("Fizz"); // return control as Control. var value2 = @this.FindControlRecursive<Literal>("Buzz"); // return control as Literal. Control value3 = @this.FindControlRecursive("Z"); // return null; }
private static void ToggleControlVisibility(Control userControl, string controlId, bool value) { if (userControl == null || string.IsNullOrEmpty(controlId)) return; var control = userControl.FindControlRecursive(controlId); if (control != null) control.Visible = value; }
//=========================================================== Helper methods /// <summary> /// Sets the label Text property based on the formatted text is included in that property. /// </summary> /// <param name="control">The control which should contain the label with labelId.</param> /// <param name="labelId">The id of the label control withing the control.</param> /// <param name="name">The name that is displayed in the label text.</param> /// <param name="path">The path that is displayed in the label text.</param> private static void SetLabel(Control control, string labelId, string name, string path) { var label = control.FindControlRecursive(labelId) as Label; if (label == null) return; var format = label.Text; try { label.Text = String.Format(format, name, path); label.Visible = true; } catch (ArgumentNullException argumentNullException) { label.BackColor = System.Drawing.Color.Black; label.ForeColor = System.Drawing.Color.Red; label.Text = "You have a wrong formatted string in " + label.ID; Logger.WriteException(argumentNullException); } catch (FormatException formatException) { label.BackColor = System.Drawing.Color.Black; label.ForeColor = System.Drawing.Color.Red; label.Text = "You have a wrong formatted string in " + label.ID; Logger.WriteException(formatException); } }