开发者

if else string is null

开发者 https://www.devze.com 2023-02-12 07:09 出处:网络
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 field开发者_如何学JAVAs completely. However it does not work...

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 field开发者_如何学JAVAs 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?


try string.IsNullOrEmpty(AntcbatchpathTextBox.Text)


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.


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 "" ?


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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消