foreach Page.Constrols

i have some controls in page(textbox,dropdownlist)
and i some of this controls Visible Property=false, i want to this
when the Page_Load event run this codes


Answer this question

foreach Page.Constrols

  • IBuildStuff

    Thank You Andrej


  • arro239

    With a web page, it gets a bit complicated. You'll have to navigate through whole control hierarchy... Try something like:

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

    // Put somewhere on the form or in some helper class
    private
    static void CheckControls(Control parentControl)
    {

    foreach (Control control in parentControl.Controls)
    {
    if (control.HasControls())
    {
    CheckControls(control);
    }
    TextBox txt = control as TextBox;
    if (txt != null && txt.ID.StartsWith("K"))
    {
    txt.Visible = false;
    }
    }
    }

    Andrej



  • Xancholy

    Thank You Andrej thanks yes,yes,yes
    it happened


  • Lili Gao

    Can you step through code with the debugger and see what's happening You can set the breakpoint on the line:

    TextBox txt = control as TextBox; // txt will be null if control is not a TextBox

    Andrej



  • PPR

    this code good get not error,But controls in page(textboxes) still not change property.(visible or readonly)
    No affected controls.Sorry.
    Thaks for help.


  • ASI Tech

    i write this code

    foreach (Control cn in Page.Controls)

    {

    if (cn.GetType() == typeof(TextBox) && cn.ID.StartsWith("K"))

    {

    cn.Visible = false;

    }

    }

    this code runs a windows application but same code not run web application

    thanks Andrej


  • KenLinder

    That's because not all the controls on your page are textboxes... Try something like this:

    foreach(Control control in Page.Controls)
    {
        TextBox txt = control as TextBox; // txt will be null if control is not a TextBox

       
    if( txt != null && txt.ID.StartsWith("B"))
       
    {
           
    txt.Visible=false
    ;
       
    }
    }

    Andrej



  • foreach Page.Constrols