2

I have two text box. If 1 of the textbox.text is empty, the MessageBox would show to prompt user that they did not enter the fields completely. However it does not work...

This is the code:

private void tab1nextButton_Click(object sender, RoutedEventArgs e)
{
    if ((AntcbatchpathTextBox.Text == null) || (MasterbuildpropertiespathTextBox.Text == null))
    {
        System.Windows.MessageBox.Show("You have not specified the paths completely!");

    }
    else
    {
        Tabitem2.Visibility = Visibility.Visible;
        Tabcontrol1.SelectedIndex = 1;

    }
}

I tried to add breakpoint to examine the immediate values. When either one of the Textbox.Text is empty, the immediate value is "" respectively. Is there anything wrong with my code?

jeremychan
  • 4,309
  • 10
  • 42
  • 56
  • 2
    The `Text` in a `TextBox` will never be `null`. It will always have some string value. In the case of an empty `TextBox`, the `Text` property will contain the empty string `""`. – Jeff Mercado Feb 22 '11 at 08:53

5 Answers5

6

try string.IsNullOrEmpty(AntcbatchpathTextBox.Text)

ppiotrowicz
  • 4,464
  • 3
  • 32
  • 46
2

There is a difference between an empty string and a null string.

A empty textbox will have a empty string, so you have to check ...Text == "" or ...Text == string.Empty instead of ...Text == null.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
0

String.Empty and null are not the same.
In your case of an empty TextBox it will always be String.Empty.

You should check for Empty with the String.IsNullOrEmpty method:

String.IsNullOrEmpty(AntcbatchpathTextBox.Text)

or

AntcbatchpathTextBox.Text == String.Emtpy
AntcbatchpathTextBox.Text == ""


See also this SO question/answers: In C#, should I use string.Empty or String.Empty or "" ?

Community
  • 1
  • 1
Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
  • actually you can just test AntcbatchpathTextBox.Text.Length > 0 since .Text will never be null and all you'll check is to see if text contains something. – Steve Feb 23 '11 at 05:24
0

Null and Empty Strings are two different concepts. Null is a reference which does not point to any object in memory. Empty string is a zero-length string object, that is created on the heap. If you check for not null, this only checks that the reference is pointing to an object and nothing else. For empty string you should include a seperate check, or just use string.IsNullOrEmpty

Midhat
  • 17,454
  • 22
  • 87
  • 114
0

You have to check for empty strings. The code you have 'AntcbatchpathTextBox.Text == null' checks for null reference. Use this instead.

string.IsNullOrEmpty(AntcbatchpathTextBox.Text)
Eduard
  • 3,176
  • 3
  • 21
  • 31