0

i want to clear all textboxes. wrote the public function as:

public void clean(Control parent)
{
    try
    {
        foreach (Control c in parent.Controls)
        {
            TextBox tb = c as TextBox; //if the control is a textbox
            if (tb != null)//Will be null if c is not a TextBox
            {
                tb.Text = String.Empty;//display nothing
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0} Exception caught.", ex);
    }
}

in the class of the page i want it to be called i declared:

PublicFunctions pubvar = new PublicFunctions();

and i call it as

pubvar.clean(Page);

but its not working... not even throwing an error... and my textboxes arent clearing... help?

mcwyrm
  • 1,571
  • 1
  • 15
  • 27
New2This
  • 253
  • 1
  • 6
  • 22
  • When and where are you calling it? Also, your use of exception handling here is pointless. – James Nov 21 '13 at 14:03
  • What is the type of page ? what you send to function ? – user2857877 Nov 21 '13 at 14:03
  • @James im calling it after closing of my connection to the database and after i do a gridview bind. all this happens when i click save to submit the info... also y is it pointless? please explain. – New2This Nov 21 '13 at 14:10
  • It's pointless because 1. You are swallowing the exception and 2. if an exception get's thrown during that block of code then something is *fundamentally* wrong - you don't want to swallow it. Are you populating your UI anywhere else? Seems to me like you are re-populating it after you postback. – James Nov 21 '13 at 14:28

1 Answers1

0

You should use recursive loop to check all the controls.

try this code

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

public class PublicFunctions 
{
    public void Clean(Control parent)
    {
        var controls = GetAllControls(parent);

        foreach (Control c in controls)
        {
            TextBox tb = c as TextBox;
            if (tb != null)
            {
                tb.Text = String.Empty;
            }
        }
    }

    public IEnumerable<Control> GetAllControls(Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            yield return control;

            foreach (Control innerControl in control.Controls)
            {
                yield return innerControl;
            }
        }
    }
}
Surya Narayan
  • 558
  • 2
  • 16