I need to find something that is the opposite of IsNullOrEmpty
?
Here's the text line.
{
while (string.IsNullOrEmpty(TextBox.Text))
}
What is the opposite of this?
In the context of a Winforms TextBox control, you don't have to test the .Text
property for null
at all. Sadly, I can't find the documentation on this, and I fear it was a casualty of the mdsn => docs move, but I have verified it in Visual Studio.
You can verify it, too; try it. Make a simple project with a textbox, and set it's Text
to null
in code. Then check in the debugger, and you'll see it's actually set an empty string. The TextBox control is just nice that way, and so are most other stock Winforms controls.
With that in mind, the opposite of this code:
while (string.IsNullOrEmpty(TextBox.Text))
can reduce down to this:
while (TextBox.Text != "")
though you may want to also consider whitespace, which would be one of these two lines:
while (TextBox.Text.Trim() != "")
while (!string.IsNullOrWhitespace(TextBox.Text))
But now I need to bring up another point: none of these options does an Invoke
on the control, meaning this must be running on the UI thread. It's very bad to run a while()
loop like this on your UI thread. You're counting on the user to break the loop, but in the meantime you've blocked the entire user interface, where the program will have a hard time even processing the input that would eventually unblock it.
Instead, you need to handle a keypress event, or validate the textbox at the point where the user tries to initiate an action depending on the textbox value, or move this to another thread.