如何在文本框中检查只有空格的C#并在此之后执行某些操作?
答案 0 :(得分:15)
这可确保您的支票中包含多个空格。
bool hasAllWhitespace = txtBox1.Text.Length>0 &&
txtBox1.Text.Trim().Length==0;
仅检查单个空格:
bool hasSingleWhitespace = txtBox1.Text == " ";
答案 1 :(得分:5)
使用string.IsNullOrWhiteSpace
检查文本框的Text
属性。
if (string.IsNullOrWhiteSpace(myTextBox.Text) && myTextBox.Text.Length > 0)
{
// do stuff
}
如果文本框为空(或属性为null),IsNullOrWiteSpace
将返回true,则添加Length
检查可确保文本框中包含某些内容。如果文本框中只有空格,则测试组合可确保为真。
答案 2 :(得分:4)
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"\s",)) {
// do your code
}
答案 3 :(得分:3)
if (String.IsNullOrWhiteSpace(txtBox.Text))
{
// so stuff
}
答案 4 :(得分:3)
一些LINQ乐趣:
bool isWhitespace = txtBox.Text.All(char.IsWhiteSpace);
答案 5 :(得分:1)
txtBox.Text.Length == 1 && char.IsWhiteSpace( txtBox.Text.First() );
答案 6 :(得分:0)
if (txtBox.Text.equals(" ")))
{
// your code goes here
}
答案 7 :(得分:0)
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
}
答案 8 :(得分:0)
//SIMPLE WAY TO VALIDATE EMPTY SPACES
if (txtusername.Text.Contains(" "))
{
MessageBox.Show("Invalid Username");
txtusername.Clear();
txtusername.Focus();
}