Loop through all controls on asp.net webpage

后端 未结 7 1436
攒了一身酷
攒了一身酷 2020-12-01 22:17

I need to loop through all the controls in my asp.net webpage and do something to the control. In one instance I\'m making a giant string out of the page and emailing it to

7条回答
  •  无人及你
    2020-12-01 22:43

    I rather like David Finleys linq approach to FindControl http://weblogs.asp.net/dfindley/archive/2007/06/29/linq-the-uber-findcontrol.aspx

    public static class PageExtensions
    {
        public static IEnumerable All(this ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                foreach (Control grandChild in control.Controls.All())
                    yield return grandChild;
    
                yield return control;
            }
        }
    }
    

    Usage:

    // get the first empty textbox
    TextBox firstEmpty = accountDetails.Controls
        .All()
        .OfType()
        .Where(tb => tb.Text.Trim().Length == 0)
        .FirstOrDefault();
    
    // and focus it
    if (firstEmpty != null)
        firstEmpty.Focus();
    

提交回复
热议问题