21

I have a TextBox. And I want to check if it's empty.

Which way is better

if(TextBox.Text.Length == 0)

or

if(TextBox.Text == '')

?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
  • `if(TextBox.Text == "")` is better because Text might be null. – M.kazem Akhgary Dec 15 '15 at 20:36
  • 12
    You could do `if (string.IsNullOrEmpty(TextBox.Text))` – Smurfie Dec 15 '15 at 20:36
  • Possible duplicate of [Empty text box to be considered an empty string or null](http://stackoverflow.com/questions/16612057/empty-text-box-to-be-considered-an-empty-string-or-null) – Camilo Terevinto Dec 15 '15 at 20:45
  • Possible duplicate of [Check if TextBox is empty and return MessageBox?](http://stackoverflow.com/questions/6156458/check-if-textbox-is-empty-and-return-messagebox) – Epicblood Dec 15 '15 at 21:02

8 Answers8

47

You should use String.IsNullOrEmpty() to make sure it is neither empty nor null (somehow):

if (string.IsNullOrEmpty(textBox1.Text))
{
    // Do something...
}

More examples here.

For practical purposes you might also consider using String.IsNullOrWhitespace() since a TextBox expecting whitespace as input probably negates any purpose, except in case of, say, letting the user pick a custom separator for stuff.

AnasSafi
  • 5,353
  • 1
  • 35
  • 38
Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
8

I think

string.IsNullOrEmpty(TextBox.Text)

or

string.IsNullOrWhiteSpace(TextBox.Text)

are your best options.

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
  • 4
    I think `string.IsNullOrWhitespace` is probably better because it fits most people's idea of what "empty" means. – Steven Rands Dec 16 '15 at 14:08
  • I agree, it's not often that a couple of spaces is an expected input from a user. – PiotrWolkowski Dec 16 '15 at 14:23
  • Been using IsNullOrEmpty on my humble c# shop app and was a fatal decision as now I have supplier names with different types of white spaces by the lazyness of my workers, the IsNullOrWhiteSpace solved everything. – WhySoSerious Jan 15 '23 at 19:44
2

If one is in XAML, one can check whether there is text in a TextBox by using IsEmpty off of Text property.

Turns out that it bubbles down to CollectionView.IsEmpty (not on the string property) to provide the answer. This example of a textbox watermark, where two textboxes are displayed (on the editing one and one with the watermark text). Where the style on the second Textbox (watermark one) will bind to the Text on the main textbox and turn on/off accordingly.

<TextBox.Style>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding ElementName=tEnterTextTextBox, Path=IsKeyboardFocusWithin}" Value="False" />
                    <Condition Binding="{Binding ElementName=tEnterTextTextBox, Path=Text.IsEmpty}" Value="True" />
                </MultiDataTrigger.Conditions>
                <Setter Property="Visibility" Value="Visible" />
            </MultiDataTrigger>
            <DataTrigger Binding="{Binding ElementName=tEnterTextTextBox, Path=IsKeyboardFocusWithin}" Value="True">
                <Setter Property="Visibility" Value="Hidden" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=tEnterTextTextBox, Path=Text.IsEmpty}" Value="False">
                <Setter Property="Visibility" Value="Hidden" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
1

You can put that code in the ButtonClick event or any event:

//Array for all or some of the TextBox on the Form
TextBox[] textBox = { txtFName, txtLName, txtBalance };

//foreach loop for check TextBox is empty
foreach (TextBox txt in textBox)
{
    if (string.IsNullOrWhiteSpace(txt.Text))
    {
        MessageBox.Show("The TextBox is empty!");
        break;
    }
}
return;
Shams Tech
  • 105
  • 8
0

Another way:

    if(textBox1.TextLength == 0)
    {
       MessageBox.Show("The texbox is empty!");
    }
D J
  • 845
  • 1
  • 13
  • 27
0

Here is a simple way

If(txtTextBox1.Text ==“”)
{
MessageBox.Show("The TextBox is empty!");
}
Aruna Prabhath
  • 206
  • 2
  • 10
-1

Farhan answer is the best and I would like to add that if you need to fullfil both conditions adding the OR operator works, like this:

if (string.IsNullOrEmpty(text.Text) || string.IsNullOrWhiteSpace(text.Text))
{
  //Code
}

Note that there is a difference between using string and String

  • -1: This is unnecessary. `string.IsNullOrWhiteSpace` checks everything that `string.IsNullOrEmpty` checks. From MSDN: "String.IsNullOrWhiteSpace: Indicates whether a specified string is null, empty, or consists only of white-space characters.". Also, since string is an alias for System.String, there's no difference between them unless they decide to change the implementation of String in a way that impacts this. Edit: It's generally encouraged to use the aliases, but that doesn't mean there's a difference. – Manuel Hoffmann Dec 18 '17 at 14:47
  • It's different trust me! I used this code when I replied, Null or white doesn't throw exception when you add a non printable such as NCHAR(0x00A0) thus you need Null or empty – Roberto Torres Dec 18 '17 at 23:35
  • 1
    Yes, it's different, since one checks for whitespace and the other does not. But if you don't want to permit whitespace, using just `string.isNullOrWhiteSpace` for the validation is enough, since it also checks for null or empty. Also, I tried both functions with '\u00A0' (non-breaking space) and neither "threw an exception". So I fail to see your point. Could you explain further? – Manuel Hoffmann Dec 19 '17 at 10:43
  • if the user adds any non printable character by copy and paste the white character will avoid null or white and enter the database – Roberto Torres Dec 19 '17 at 22:44
  • In the case of \u00A0, during my test, it is correctly recognized as a whitespace character in `string.IsNullOrWhiteSpace`. Do you have any example for other non-printable characters that won't be recognized as whitespace? – Manuel Hoffmann Dec 20 '17 at 08:07
-2

In my opinion the easiest way to check if a textbox is empty + if there are only letters:

public bool isEmpty()
    {
        bool checkString = txtBox.Text.Any(char.IsDigit);

        if (txtBox.Text == string.Empty)
        {
            return false;
        }
        if (checkString == false)
        {
            return false;
        }
        return true;
    }
Guest28512
  • 21
  • 1
  • 1
    The OP was only asking about an empty textbox. This answer adds an extra layer of logic that was not asked about. Also, there are a few bugs in the code from what I can tell. If the textbox is empty then the IsEmpty function returns false. If the textbox contains only '1' then IsEmpty returns true. – Nathan Werry Aug 16 '21 at 13:12