简体   繁体   English

C#检查文本框中的空白区域

[英]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 . 使用string.IsNullOrWhiteSpace检查Text框的Text属性。

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. 如果文本框为空(或属性为null),则IsNullOrWiteSpace将返回true,因此添加“ Length检查可确保文本框中存在某些内容。 The combination of the tests ensures a true if there is only whitespace in the textbox. 如果文本框中只有空格,则测试的组合可确保为true。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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