Is it even possible for the text property of a TextBox to be null?

天涯浪子 提交于 2019-12-11 13:12:14

问题


I came across this code:

if (txtUPC.Text.ToString() != null)

...and wonder if this test is even valid - is it possible for the text property to be null? txtUPC is not a dynamically created control. It can be empty, of course, or contain just whitespace, but null? If so, I'd like to know how. Then again, call ToString() on the text property seems like wearing suspenders with a belt, too.

UPDATE

So it seems to me, that for me (remember: .NET 1.1, Windows CE/Compact Framework), this:

if (txtUPC.Text.Trim() != string.Empty)

...is a better test than this:

if (txtUPC.Text.ToString() != null) 

However, upon gazing even more intently at this code, it seems that either the outer or the inner gauntlet is redundant/unnecessary, anyway. Note the two shibbeleth-pronunciation-checkers that the method includes:

if (txtUPC.Text.ToString() != null) 
{
    if (txtUPC.Text.Length > 0)
    {
                    . . .
    else
    {
        MessageBox.Show("Please enter a value in the item field");
        txtUPC.Focus();
    }
}
else
{
    MessageBox.Show("Please enter a value in the item field");
    txtUPC.Focus();
}
. . .

It would seem one gatekeeper/gauntleteer would be enough - either checking this way:

if (txtUPC.Text.Trim() != string.Empty)

...or this way:

if (txtUPC.Text.Trim().Length > 0)

a?


回答1:


The problem I see with that code is that .ToString() returns the object as a String. If in this case, the object is a String it just returns the original string (exactly as is)

Problem is if .Text is null, then the method call of .ToString() would throw a NullReferenceException.

You can see more on the .ToString override here

See this code for an example:

String str1 = "";
String str2 = null;

Console.WriteLine("Original str1: {0}", str1);
Console.WriteLine("Original str2: {0}", str2);

Console.WriteLine("ToString str1: {0}", str1.ToString());
Console.WriteLine("ToString str2: {0}", str2.ToString());

Will throw the exception on the ToString str2 line




回答2:


I don't think it could ever be null (perhaps there is a difference between a winforms/asp.net/wpf textbox, but I don't think so). Although a better check would be:

if (String.IsNullOrEmpty(txtUPC.Text) { ... }

Or, depending on your requirements:

if (String.IsNullOrWhiteSpace(txtUPC.Text) { ... }

And yes, the .ToString() is not needed.



来源:https://stackoverflow.com/questions/18839129/is-it-even-possible-for-the-text-property-of-a-textbox-to-be-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!