validationWindows窗体应用程序中的文本框

我的情景是:

输入一个或多个字符后,不允许在文本框的起始位置使用空格文本框允许使用空格

以下不适用于我的场景。

  1. private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = (e.KeyChar == (char)Keys.Space)) { MessageBox.Show("Spaces are not allowed"); } } 
  2.  textBox1.Text.TrimStart() 

我相信lazyDBA的答案对你的要求是正确的,所以在消息框中就像这样:

 if (textBox1.Text.Length == 0) { if (e.Handler = (e.KeyChar == (char)Keys.Space)) { MessageBox.Show("space not allowed!"); } }` 
 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) \ { if(textBox1.Text.Length == 0) { if (e.Handled = (e.KeyChar == (char)Keys.Space)) { MessageBox.Show("Spaces are not allowed at start"); } } } 

你没有简单描述,如果我没有错,你想在开始时修剪空格?

那么我的答案是,你可以通过多种方式处理它,一种可能的方法是以下列方式处理它。 我在下面写的一些示例代码,您可以查看它,它在我的示例应用程序中运行完美:

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if ((textBox1.SelectionStart == 0) && (e.KeyChar == (char)Keys.Space)) { e.Handled = true; } } private void textBox1_TextChanged(object sender, EventArgs e) { //Store the back up of Current Cursor Possition. int cusorpos = textBox1.SelectionStart; if (false == string.IsNullOrEmpty(textBox1.Text)) { if (textBox1.Text[0] == ' ') { //Trim Spaces at beginning. textBox1.Text = textBox1.Text.TrimStart(' '); //Set the Cursor position to current Position. textBox1.SelectionStart = cusorpos; } } } 

正如你在这里看到的,我写了两个事件,因为如果任何正文在开头粘贴带有空格的文本,那么在你的文本框控件中它将完美地从头开始删除空格。

你说第一个选项不适用。 第一个选项的版本如何使用相同的事件和类似的代码,但在第二个IF语句中。 除非文本框中还有其他字符,否则这将使空格无法工作。

 if (textBox1.Text.Length == 0) { e.Handled = (e.KeyChar == (char)Keys.Space)) } 

尝试

  private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = (e.KeyChar == (char)Keys.Space)) { if(((TextBox)sender).Text.Replace(" ","") == "") { MessageBox.Show("Spaces are not allowed"); ((TextBox)sender).Text = string.Empty; } } } 

KeyPress事件中尝试此操作

 if ((sender as TextBox).Text.Length <= 0) e.Handled = (e.KeyChar == (char)Keys.Space); else e.Handled = false; 

万一你必须让它工作,如果用户输入一些文本后移动到TextBox字段的开头并尝试输入空格,那么这也将禁用它

 void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if ((sender as TextBox).SelectionStart == 0) e.Handled = (e.KeyChar == (char)Keys.Space); else e.Handled = false; } 

你应该使用正则表达式

  string strRegex = @"^([\w]+.*)$"; string strTargetString = textBox1.Text; if (!Regex.IsMatch(strTargetString, strRegex)) { // show error that spase not allow at the bigin of string }