如何使用for循环扫描ASP .NET中页面中的所有控件? [英] How to use for loop to scan all controls in page in ASP .NET?

查看:77
本文介绍了如何使用for循环扫描ASP .NET中页面中的所有控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用for循环扫描ASP .NET中页面中的所有控件?

How to use for loop to scan all controls in page in ASP .NET?

我想在一个for循环中验证所有文本框的文本

as i would like to validate all textboxs' text in one for loop

推荐答案

最简单的解决方案是将验证器添加到文本框中(即RequiredFieldValidator).它们允许您指定自定义错误消息,并且可以通过在后面的代码中简单地调用Page.Validate()进行检查.

The easiest solution would be to add Validators to the text box (ie, RequiredFieldValidator). They allow you to specify custom error messages and can be checked by simply calling Page.Validate() in your code behind.

如果这不是一个选择,则ASP.Net控件嵌套在层次结构中,因此您将需要使用一些递归来拾取页面上的每个文本框.以下功能代码循环浏览页面上的所有控件集合,并在文本框为空时附加错误消息.

If that is not an option, ASP.Net controls are nested in a hierarchy, so you will need to use some recursion to pick up every textbox on the page. The following function code loops through all the control collections on the page and appends an error message when the textbox is empty.

protected void buttonClick(object sender, EventArgs e)
{
    List<String> errors = new List<String>();
    ValidateTextboxes(errors, this.Controls);
    if (errors.Count > 0)
    {
        // Validation failed
    }
}

protected void ValidateTextboxes(List<String> errors, ControlCollection controls)
{
    foreach (Control control in controls)
    {
        if (control is TextBox)
        {
            // Validate
            TextBox tb = control as TextBox;
            if (tb.Text.Length == 0)
                errors.Add(tb.ID + ": field is required:");
        }

        if (control.Controls.Count > 0)
            ValidateTextboxes(errors, control.Controls);
    }
}

这篇关于如何使用for循环扫描ASP .NET中页面中的所有控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆