Wednesday, June 20, 2007
« Kudos for Comcast | Main | Outlook and RSS »

I have been using this little piece of code to recursively search my control collections for a given control or type of controls and thought that it might be of some use to others. The general purpose utility code is here:

public static void SearchControls(ControlCollection controls, Action<Control> action)

{

    foreach (Control control in controls)

    {

        if (control.HasControls())

        {

            SearchControls(control.Controls, action);

        }

        action(control);

    }

}

 

For example, if you want to search for and Trim() all TextBox controls within a GridView, you could call the routine as follows using an anonymous method:

 

SearchControls(GridViewJobs.Controls, delegate(Control control)

{

    TextBox textBox = control as TextBox;

    if (textBox != null)

    {

        textBox.Text = textBox.Text.Trim();

    }

});

 

If you need to search a GridView footer for a drop down list, you call the code as follows:

 

ControlUtility.SearchControls(gvwOrganizations.FooterRow.Controls, delegate(Control control)

{

    DropDownList dropDownListCategory = control as DropDownList;

    if (dropDownListCategory != null)

    {

        categoryID = int.Parse(dropDownListCategory.SelectedValue);

    }

});

 

 

kick it on DotNetKicks.com   Wednesday, June 20, 2007 8:01:19 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  |