Check Whether a TextBox is empty or not
Asked Answered
W

8

22

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 == '')

?

World answered 15/12, 2015 at 20:32 Comment(4)
if(TextBox.Text == "") is better because Text might be null.Bilicki
You could do if (string.IsNullOrEmpty(TextBox.Text))Pneumograph
Possible duplicate of Empty text box to be considered an empty string or nullIrv
Possible duplicate of Check if TextBox is empty and return MessageBox?Enduring
W
50

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.

Wasting answered 15/12, 2015 at 20:49 Comment(0)
W
8

I think

string.IsNullOrEmpty(TextBox.Text)

or

string.IsNullOrWhiteSpace(TextBox.Text)

are your best options.

Waldos answered 16/12, 2015 at 2:36 Comment(3)
I think string.IsNullOrWhitespace is probably better because it fits most people's idea of what "empty" means.Pyrophoric
I agree, it's not often that a couple of spaces is an expected input from a user.Waldos
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.Magnetism
M
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>

Mcclintock answered 17/1, 2020 at 22:39 Comment(0)
S
1

Another way:

    if(textBox1.TextLength == 0)
    {
       MessageBox.Show("The texbox is empty!");
    }
Steelmaker answered 1/4, 2020 at 18:29 Comment(0)
N
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;
Nonunionism answered 14/6, 2021 at 4:33 Comment(0)
W
0

Here is a simple way

If(txtTextBox1.Text ==“”)
{
MessageBox.Show("The TextBox is empty!");
}
Winograd answered 26/11, 2022 at 3:59 Comment(0)
B
-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

Basrelief answered 1/11, 2017 at 17:32 Comment(5)
-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.Davison
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 emptyBasrelief
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?Davison
if the user adds any non printable character by copy and paste the white character will avoid null or white and enter the databaseBasrelief
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?Davison
J
-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;
    }
Jacaranda answered 16/8, 2021 at 12:50 Comment(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.Myranda

© 2022 - 2024 — McMap. All rights reserved.