Toars I will smile to the world ^o^

17Mar/101

FindControl() extension methods, FindControl(), FindControlsByType() and FindControlRecursive()

Imagine, you have 20 TextBox in your page, you want to empty each of the TextBox value. How you are going to do it?

Is it perfect to do the job this way?

var txtControls = this.FindControlByType<TextBox>();

foreach (var control in txtControls)
{
	control.Text = string.Empty;
}

.NET only offers us FindControl(), what we need is to create some extension methods that can extend the functionalities, such as FindControlsByType() and FindControlRecursive().

private static void FindChildControlsByType<TControl>(this Control root, List<TControl> childControls) where TControl: Control
{
	foreach (Control control in root.Controls)
	{
		if (control.GetType() == typeof(TControl))
			childControls.Add((TControl)control);

		FindChildControlsByType<TControl>(control, childControls);
	}
}

public static List<TControl> FindControlByType<TControl>(this Control root) where TControl: Control
{
	var childControls = new List<TControl>();

	FindChildControlsByType<TControl>(root, childControls);

	return childControls;
}

To an extend, here are another extension methods that I am using very often.


public static TControl FindControlRecursive<TControl>(this Control root, string id) where TControl : Control
{
	if (root.ID == id)
	return (TControl) root;

	foreach (Control ctl in root.Controls)
	{
		Control foundCtl = (TControl) ctl.FindControlRecursive<TControl>(id);

		if (foundCtl != null)
			return (TControl) foundCtl;
	}

	return null;
}

public static TControl FindControl<TControl>(this Control control, string id) where TControl : Control
{
	return (TControl) control.FindControl(id);
}
Filed under: .NET, C# 1 Comment