locked
Clear text of all textboxes in a form inside buttonClear_Click RRS feed

  • Question

  • Hi,

    Using c#, I have a form with few textboxes, a button clear to clear all text inside of each textbox when I click this button.

    My code is as below

    private void btnClear_Click(object sender, EventArgs e)

    {

        foreach (Control ctrl in this.Controls)

        {

            TextBox tb = ctrl as TextBox;

            if (tb.Text != string.Empty)  //error at this line.

               tb.Clear();

         }

    }

    /////

    When I compile, it 's fine.  But when I run my code, there is an error at checking the textbox is not empty string.

    error stated "Object reference not set to an instance of an object."  How do I correct my problem?

    I can do single line code to call clear() method for single textbox at a time.  However, I want to make a short way to handle this incase there are a lot of textboxes in a form.

    All helps are appreciated.

    Thanks,

    tt.

    Thursday, September 27, 2012 4:41 PM

Answers

  • Hi,

    Replace your condition with this
     if (tb!=null && tb.Text != string.Empty)

    The error is occuring since your control from your list of controls might not be able to cast to the type of Textbox.

    Thanks,

    BR,

    JollyWagoner

    • Marked as answer by Bob Wu-MT Friday, September 28, 2012 2:16 AM
    Thursday, September 27, 2012 5:03 PM
  • Actually, I did code the condition if(tb != null && tb.Text != string.Empty), then I changed my mind : -)

    Well, it works now.

    thank you!

    regards,

    tt.

    • Marked as answer by tt-2010 Thursday, September 27, 2012 5:42 PM
    Thursday, September 27, 2012 5:41 PM

All replies

  • Why you need to check for empty string? No need, so do:

    foreach (Control ctrl in this.Controls.OfType<TextBox>()) //add last code to select only textBoxes!
    {
       ctrl.Text = "";
    }


    Mitja

    Thursday, September 27, 2012 4:57 PM
  • Hi,

    Replace your condition with this
     if (tb!=null && tb.Text != string.Empty)

    The error is occuring since your control from your list of controls might not be able to cast to the type of Textbox.

    Thanks,

    BR,

    JollyWagoner

    • Marked as answer by Bob Wu-MT Friday, September 28, 2012 2:16 AM
    Thursday, September 27, 2012 5:03 PM
  • Thats why I implemented an additional code in the 1st line of code ( to select only textBoxes).

    But you are right, the problem is because he is trying to check for Text property even if its null.


    Mitja

    Thursday, September 27, 2012 5:06 PM
  • Actually, I did code the condition if(tb != null && tb.Text != string.Empty), then I changed my mind : -)

    Well, it works now.

    thank you!

    regards,

    tt.

    • Marked as answer by tt-2010 Thursday, September 27, 2012 5:42 PM
    Thursday, September 27, 2012 5:41 PM