C# – Find Textbox control

asp.netc

In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly

foreach (Control cntrl in Page.Controls)
    {
        if (cntrl is TextBox)
        {
            //Do the operation
        }
    }

<%@ Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

Best Answer

I've recently started doing this the 'modern' LINQ way. First you need an extension method to grab all the controls of the type you're interested in:

//Recursively get all the formControls  
public static IEnumerable<Control> GetAllControls(this Control parent)  
{  
     foreach (Control control in parent.Controls)  
        {  
            yield return control;  
            foreach (Control descendant in control.GetAllControls())  
            {  
                yield return descendant;  
            }  
     }  
}`  

Then you can call it in your webform / control:

var formCtls = this.GetAllControls().OfType<Checkbox>();

foreach(Checkbox chbx in formCtls){

//do what you gotta do ;) }

Regards,
5arx

Related Topic