How to use for loop to scan all controls in page in ASP .NET?
as i would like to validate all textboxs' te开发者_高级运维xt in one for loop
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.
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);
}
}
When I used to use WebForms, I had an extension method I'd created:
public static class PageExtensions
{
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
{
yield return grandChild;
}
yield return control;
}
}
}
And to use it to select all TextBoxes on a page:
this.Form.Controls
.All()
.OfType<TextBox>()
.ToList()
.ForEach(t => Validate(t.Text));
There are several ways you can do this. You could do it with recursion using the base Control class, starting from whatever point necessary and referencing controlInstance.Controls to get the child controls testing to see if they are textboxes. This is not optimal.
You could also keep a list of references to these textboxes, and loop through them using that. This is faster and more efficient. You can do the same thing with an array of strings and FindControl.
You could also use the built in validators so you don't have to it. There are limits though, of course.
精彩评论