How can I check in C# that is there a white space only in a textbox and perform some operation after that?
if (txtBox.Text.equals(" ")))
{
// your code goes here
}
//SIMPLE WAY TO VALIDATE EMPTY SPACES
if (txtusername.Text.Contains(" "))
{
MessageBox.Show("Invalid Username");
txtusername.Clear();
txtusername.Focus();
}
txtBox.Text.Length == 1 && char.IsWhiteSpace( txtBox.Text.First() );
Check the Text property of the textbox using string.IsNullOrWhiteSpace.
if (string.IsNullOrWhiteSpace(myTextBox.Text) && myTextBox.Text.Length > 0)
{
// do stuff
}
Since IsNullOrWiteSpace will return true if the textbox is empty (or the property is null), adding the Length check ensures that there is something within the text box. The combination of the tests ensures a true if there is only whitespace in the textbox.
Some LINQ fun:
bool isWhitespace = txtBox.Text.All(char.IsWhiteSpace);
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"\s",)) {
// do your code
}