Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to find control in ASP.NET

I have a complex asp.net form,having even 50 to 60 fields in one form like there is Multiview, inside MultiView I have a GridView, and inside GridView I have several CheckBoxes.

Currently I am using chaining of the FindControl() method and retrieving the child ID.

Now, my question is that is there any other way/solution to find the nested control in ASP.NET.

like image 723
santosh singh Avatar asked Feb 10 '11 10:02

santosh singh


People also ask

What is ASP.NET find control?

The FindControl method can be used to access a control whose ID is not available at design time. The method searches only the page's immediate, or top-level, container; it does not recursively search for controls in naming containers contained on the page.

What is C# Find control?

FindControl(String, Int32)Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search.


2 Answers

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary> /// Finds all controls of type T stores them in FoundControls /// </summary> /// <typeparam name="T"></typeparam> private class ControlFinder<T> where T : Control  {     private readonly List<T> _foundControls = new List<T>();     public IEnumerable<T> FoundControls     {         get { return _foundControls; }     }          public void FindChildControlsRecursive(Control control)     {         foreach (Control childControl in control.Controls)         {             if (childControl.GetType() == typeof(T))             {                 _foundControls.Add((T)childControl);             }             else             {                 FindChildControlsRecursive(childControl);             }         }     } } 
like image 132
jimmystormig Avatar answered Oct 14 '22 23:10

jimmystormig


Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)                                                         where T : Control {     foreach (Control child in parent.Controls)     {         if (child is T)         {             yield return (T)child;         }         else if (child.Controls.Count > 0)         {             foreach (T grandChild in child.FindControlsOfType<T>())             {                 yield return grandChild;             }         }     } } 
like image 31
David Clarke Avatar answered Oct 14 '22 22:10

David Clarke