C#: How to find an empty string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JFKJr
    New Member
    • Jul 2008
    • 126

    C#: How to find an empty string

    Hello Guys,

    I have a textbox called "NameTextBo x" and "Submit" button in my "index.aspx " page.

    I need to check whether user entered name in the textbox before clicking submit button.

    And, this is what I did:

    Code:
    string name = NameTextBox.Text.ToString();
    if (name.Length == 0)
    {
       return;
    }
    But if the user enters spaces in the textbox, I am unable to check the string as empty.

    Please let me know how to solve this issue.
    Thanks.
  • JFKJr
    New Member
    • Jul 2008
    • 126

    #2
    Solved the problem by using Trim() Method, but ran into another problem.

    Using Trim() method, I am removing all spaces in a string including spaces between words. But, I only want to remove spaces at the beginning of the string. How can I do this?

    Any help/idea will be greatly appreciated.
    Thanks.

    Comment

    • jg007
      Contributor
      • Mar 2008
      • 283

      #3
      try Trimstart -

      Example_String. TrimStart(' ')

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        Alternative check

        I've kinda followed this format in a lot of places

        Code:
                private void testing()
                {
                    string szFirst = tbFirstName.Text;
                    bob.Trim(); // By definition "removes all trailing and leading whitespace characters"
                    if (string.IsNullOrEmpty(szFirst )) { /* do nothing */ }
                    else
                    {
                        // do somthing here
                    }
                }
        If you only trim the start, you don't catch trailing whitespace.
        If you only trim ' ', you only trim out the ASCII 32 {space] character, not all forms of whitespace.

        As for trimming the space between first and last name...
        Use different boxes then combine them if you need a combined field.
        In the real world not everyone is "John Smith". You have to take into consideration people with hyphenated to two part last names... someone who under "name" would enter first, middle, last... or people who might enter "last, first i."... So guide them with a well thought-out form that doesn't leave room for interpretation. Besides, you're going to want their last name as a separate field at some point so you can sort data, or their first name by it self for a friendly salutation.

        Comment

        Working...