简体   繁体   中英

C# checking white space in a textbox

如何在文本框中检查只有空格的C#并在此之后执行一些操作?

This ensures multiple spaces are caught in your check.

 bool hasAllWhitespace = txtBox1.Text.Length>0 &&
                         txtBox1.Text.Trim().Length==0;

To check for a single space only:

 bool hasSingleWhitespace = txtBox1.Text == " ";

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.

if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"\s",)) {
    // do your code
}
if (String.IsNullOrWhiteSpace(txtBox.Text))
{
    // so stuff
}

一些LINQ乐趣:

bool isWhitespace = txtBox.Text.All(char.IsWhiteSpace);
txtBox.Text.Length == 1 && char.IsWhiteSpace( txtBox.Text.First() );
        var Rxwhitesp = new Regex(@"\s");

        string textboxstring = textbox.Text;
        string textboxfirststring = textbox.Text.First().ToString();
        if (Rxwhitesp.IsMatch(textboxfirststring) && (textboxstring.Length == 1))
        {
            // write code for true condition
        }
        else
        {
            // write code for false condition
        }
//SIMPLE WAY TO VALIDATE EMPTY SPACES
if (txtusername.Text.Contains(" "))
{
    MessageBox.Show("Invalid Username");
    txtusername.Clear();
    txtusername.Focus();
}
if (txtBox.Text.equals(" ")))
{
 // your code goes here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM