Callum Sangray Callum Sangray - 3 months ago 30
C# Question

Textbox Leave event

private void ExtTextbox_Leave(object sender, EventArgs e)
{
TextBox box = (TextBox)sender;
if (box.Text != null)
{
ext = box.Text;
}
else
{
ext = null;
box.Text = "Please enter";
MessageBox.Show(ext); //debugging purposes
}
}


I have an issue that if the text box has nothing inside of of it, I want it to fill up with 'Please enter' when the user leaves the textbox. But this code never gets into 'else'. Can someone explain why? I feel like its simple, but I genuinely can't see it.

Answer

You should use:

if (!string.IsNullOrEmpty(box.Text))

instead of

if (box.Text != null)

string.IsNullOrEmpty checks for both null value and empty string

As Geoff James suggested in comments you may also want to check for white spaces by using string.IsNullOrWhiteSpace method.