Tech Off Thread

18 posts

Clear All Textboxes On A Form

Back to Forum: Tech Off
  • User profile image
    PeterH

    How would I go about clearing the value of all the texboxes on my form. I'm using the .net Framework 2.0 with C#. This is the code I tryed which didn't work (no error, just no result):


    for
    (int i = 0; i < this.Controls.Count; i++ )

    {

       if (this.Controls[i] is TextBox)

       {

          this.Controls[i].Text = " ";

       }

    }


    Thanks in advance.

  • User profile image
    Manip

    Works perfectly for me. Please provide more code.

  • User profile image
    yyy

    Try this:

    foreach(Control control in this.Controls)

    {

    if(control.GetType() == typeof(TextBox))

    {

    control.Text = "";

    }

    }

  • User profile image
    PeterH

    Manip wrote:
    Works perfectly for me. Please provide more code.



    Sure:

    namespace vintageMotors

    {

    public partial class mainForm : Form

    {

    public mainForm()

    {

    InitializeComponent();

    ;

    }

    #region Add Car Field Validation

    private void addMileageText_keyPress(object sender, KeyPressEventArgs e)

    {

    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)

    {

    e.Handled = true;

    errorProvider.SetError(addMileageText, "Numerical values only");

    }

    else

    {

    errorProvider.SetError(addMileageText, "");

    }

    }

    private void addYearText_keyPress(object sender, KeyPressEventArgs e)

    {

    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)

    {

    e.Handled = true;

    errorProvider.SetError(addYearText, "Numerical values only");

    }

    else

    {

    errorProvider.SetError(addYearText, "");

    }

    }

    private void addSellerPriceText_keyPress(object sender, KeyPressEventArgs e)

    {

    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)

    {

    e.Handled = true;

    errorProvider.SetError(addSellerPriceText, "Numerical values only");

    }

    else

    {

    errorProvider.SetError(addSellerPriceText, "");

    }

    }

    private void addSellerPhoneText_keyPress(object sender, KeyPressEventArgs e)

    {

    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar != (char)43 && e.KeyChar != (char)32)

    {

    e.Handled = true;

    errorProvider.SetError(addSellerPhoneText, "Numerical values only");

    }

    else

    {

    errorProvider.SetError(addSellerPhoneText, "");

    }

    }

    #endregion

    Car car = new Car();

    private void addSubmitButton_Click(object sender, EventArgs e)

    {

    car.Make = addMakeText.Text;

    car.Model = addModelText.Text;

    car.Year = Convert.ToInt32(addYearText.Text);

    car.InitialMileage = Convert.ToInt32(addMileageText.Text);

    car.Description = addDescriptionText.Text;

    backgroundWorker.RunWorkerAsync();

    }

    private void backgroundWorker_doWork(object sender, DoWorkEventArgs e)

    {

    serializeObject(car, "DataStore.xml");

    }

    private void backgroundWorker_runWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

    {

    for (int i = 0; i < this.Controls.Count; i++ )

    {

    if (this.Controls[i] is TextBox)

    {

    this.Controls[i].Text = " ";

    }

    }

    MessageBox.Show("New car has been added to the data store successfully!", "New Car Added", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }

    public void serializeObject(Car car, string file)

    {

    // Create collection of Car objects

    List<Car> carList = new List<Car>();

    // Retrieve current Car data

    XmlSerializer serializer = new XmlSerializer(typeof(List<Car>));

    if (File.Exists(file) == true)

    {

    FileStream fileStream = new FileStream(file, FileMode.Open);

    XmlReader reader = new XmlTextReader(fileStream);

    carList = (List<Car>)serializer.Deserialize(reader);

    reader.Close();

    fileStream.Close();

    }

    // Add new Car object to collection

    carList.Add(car);

    // Re-serialize Car collection

    File.Delete(file);

    TextWriter writer = new StreamWriter(file, true);

    serializer.Serialize(writer, carList);

    writer.Close();

    }

    }

    }


    I've highlighted the code I was talking about in bold.

  • User profile image
    Frank Hileman

    You probably have another Control container between your Form and TextBoxes. Look at the hierarchy in InitializeComponent -- you may need a recursive method to dig into each control container and find TextBoxes.

  • User profile image
    PeterH

    Not sure what you mean. You probably won't have the time to take a look, but if you do here is the link to the Visual Studio 2005 Project:

    Project File

  • User profile image
    W3bbo

    PeterH wrote:


    ICT Classwork, right? Wink

    Welcome to the most tedious and least-important part of your academic history (spare Yr.8 of course) in your life Smiley

  • User profile image
    Manip

    You have containers in the groups you are using, addSellerDetailsBox and addCarTab, those have their own *.Controls.

    A groupBox is just a form without any controls on the top right or the ability to add menus. So if you have a textBox inside a groupBox that is like having another form so when you call it on the form all that form is able to find is the group boxes. 

    Try this: 

      for (int i = 0; i < this.Controls.Count; i++)
                {

                    if (this.Controls[i] is TextBox)
                    {
                        this.Controls[i].Text = " ";
                    }
                    else if(this.Controls[i] is GroupBox)
                    {
                        for (int y = 0; y < this.Controls[i].Controls.Count; y++)
                        {
       if (this.Controls[i].Controls[y] is TextBox)
                     {
                          this.Controls[i].Controls[y].Text = " ";
                     }
                           
                        }
                    }

                }

  • User profile image
    wacko

    i think we all where on the right page but if you actually looked at his code you would see that he has all these controls on a tabpage in a tabcontrol and for some reason this.controls was only finding the submit button, but knowing that they are all in tabpages the following works just fine.

    foreach (TabPage t in this.tabControl.TabPages)
                {
                    foreach (Control c in t.Controls)
                    {
                        if (c is GroupBox)
                        {
                            for (int i = 0; i < c.Controls.Count; i++)
                            {
                                if (c.Controls[i] is TextBox)
                                {
                                    c.Controls[i].Text = "";
                                }
                            }
                        }
                    }
                }

    It will look at the tabcontrol and then go through all the tabpages and then go through that for groupbox's and then go through that for the textbox's

  • User profile image
    PeterH

    Thanks Wacko, that works great. I understand now, I didn't know that that was how Windows Forms worked. i.e. With control hierachies.


    Orbit86 wrote:

    name.text ="" ..its not like you have 500 textboxs..do you?



    Only ten at the moment Tongue Out But I still think it is better coding. Also it's good practice for future programming I might do that needs this extra functionallity. And as I said above, it has taught me something I didn't know about windows forms.

    Thanks for all your comments,

    PeterH

  • User profile image
    dwoodard

    Not to beat a dead horse, but if you are looking for a slightly more generic approach, you could write something like this.

    private void ClearTextBoxes(Control parent)
    {

        if(parent is TextBox)
        {
            //using String.Empty is better than ""
            //because it is static so there is only one allocation
         parent.Text = String.Empty;
        }

        foreach(Control control in parent.Controls)
       {
            if(control is TextBox)
            {
               
                control.Text = String.Empty;
            }

            if(control.Controls.Count > 0)
            {
                 ClearTextBoxes(control);
            }
    }
     
    This would allow you to pass in the parent form, a single tab, a group box a panel or whatever control that could possibly contain a text box.

    Perhaps it is overkill, but since you asked. Smiley

  • User profile image
    Maurits

    dwoodard wrote:

    //using String.Empty is better than ""
    //because it is static so there is only one allocation

    Developer fatigue is also a concern though Smiley

  • User profile image
    cseeger

    why not make it recursive? check to see if the control has a contol collection...

    then just call its self.......

    private void clearTheTextBoxes(Control containerControl){
        foreach (contol ctl in containerControl.controls){
           if(ctl.controls.count > 0)
                  clearTheTextBoxes(ctl);
           else
                  if(ctl = typeof(TextBoxBase))
                       ctl.Text = string.empty;
        }
    }
       
    -chad

  • User profile image
    dwoodard

    I am using recursion. I was just trying to avoid the time when a TextBox can contain other controls. Whis is terrifying, but possible in Avalon.

    Your version certainly works though.

  • User profile image
    PeterH

    dwoodard wrote:
    Not to beat a dead horse, but if you are looking for a slightly more generic approach, you could write something like this.

    private void ClearTextBoxes(Control parent)
    {

        if(parent is TextBox)
        {
            //using String.Empty is better than ""
            //because it is static so there is only one allocation
         parent.Text = String.Empty;
        }

        foreach(Control control in parent.Controls)
       {
            if(control is TextBox)
            {
               
                control.Text = String.Empty;
            }

            if(control.Controls.Count > 0)
            {
                 ClearTextBoxes(control);
            }
    }
     
    This would allow you to pass in the parent form, a single tab, a group box a panel or whatever control that could possibly contain a text box.

    Perhaps it is overkill, but since you asked.


    I have since changed it to String.Empty for the same reason as you stated, thanks for pointing it out though!

  • User profile image
    cseeger

    dwoodward - good call, somehow that recursion in your solution just slipped right by me.

    perhaps i DO need another cup of java....errr, i mean coffee =)

    thanks!

    -chad

  • User profile image
    BMXer

    What about this:
     
            private void ClearTextBoxs()
            {
                foreach (Control c in this.pnlBody.Controls)
                {
                    if (c is TextBox)
                    {
                        TextBox tb = (TextBox)c;
                        tb.Text = string.Empty;
                    }

                    if(c is CheckBoxList)
                    {
                        CheckBoxList cb = (CheckBoxList)c;
                        cb.ClearSelection();
                    }

                    if(c is RadioButtonList)
                    {
                        RadioButtonList rb = (RadioButtonList)c;
                        rb.ClearSelection();
                    }
                }
            }


    I need to wrap it all in a panel called pnlBody. Can't find any controls if I only use this in the "foreach" statement: "this.controls"

  • User profile image
    Harlequin

    Frank Hileman wrote:
    You probably have another Control container between your Form and TextBoxes. Look at the hierarchy in InitializeComponent -- you may need a recursive method to dig into each control container and find TextBoxes.


    No, you'll have to do what Frank said above, you'll have to loop through this.Controls, and check if the control has controls, then iterate through them

    Control
    Control
         Control
                Control
    Control
         Control
               Control
                      Control
    ...etc etc etc

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.