Mathew Paul
Mathew Paul

Reputation: 663

Find Textbox control

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" %>

Upvotes: 1

Views: 9035

Answers (4)

Oleg Grishko
Oleg Grishko

Reputation: 4281

This one goes recursively, so it will run on all controls in the page. Note that if you want it to go over the textboxes in the databound controls too, you should probably call it in the OnPreRender.

protected void Page_Load(object sender, EventArgs e)
{
    ColorChange(this);
}

protected static void ColorChange(Control parent)
{
    foreach (Control child in parent.Controls)
    {
        if (child is TextBox)
            (child as TextBox).ForeColor = Color.Red;

        ColorChange(child);
    }
}

Upvotes: 1

immutabl
immutabl

Reputation: 6903

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

Upvotes: 3

TBohnen.jnr
TBohnen.jnr

Reputation: 5129

protected void setColor(Control Ctl)
{
    foreach (Control cntrl in Ctl.Controls)
    {
         if (cntrl.GetType().Name == "TextBox")
         {
              //Do Code
         }
         setColor(Control cntrl);
    }
}

You can then call this with setColor(Page)

Upvotes: 1

Lareau
Lareau

Reputation: 2011

You will probably have to recursively go through each container. This article has one method of doing it.

Upvotes: 0

Related Questions