C#检查文本框中的空白区域
如何在文本框中检查只有空格的C#并在此之后执行一些操作?
这可确保您的支票中包含多个空格。
bool hasAllWhitespace = txtBox1.Text.Length>0 && txtBox1.Text.Trim().Length==0;
仅检查单个空格:
bool hasSingleWhitespace = txtBox1.Text == " ";
使用string.IsNullOrWhiteSpace
检查Text
框的Text
属性。
if (string.IsNullOrWhiteSpace(myTextBox.Text) && myTextBox.Text.Length > 0) { // do stuff }
如果文本框为空(或属性为null),则IsNullOrWiteSpace
将返回true,因此添加“ Length
检查可确保文本框中存在某些内容。 如果文本框中只有空格,则测试组合可确保为true。
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"\s",)) { // do your code }
一些LINQ乐趣:
bool isWhitespace = txtBox.Text.All(char.IsWhiteSpace);
if (String.IsNullOrWhiteSpace(txtBox.Text)) { // so stuff }
txtBox.Text.Length == 1 && char.IsWhiteSpace( txtBox.Text.First() );
if (txtBox.Text.equals(" "))) { // your code goes here }
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(); }