我正在构建Windows Forms应用程序,并希望禁止用户将空格和其他空格输入TextBox。在发送带有“您输入了空格”之类的消息的表格后,我不想检查它。我不想使用此:
protected override void OnKeyDown(KeyEventArgs e)
Run Code Online (Sandbox Code Playgroud)
因为我必须将按下的键与所有可能的空格进行比较。有什么方法可以将设置TextBox为仅接受不是空格的字符?
龙(空白)可以Textbox通过两种方式进入您的池塘():
Text(例如借助复制+粘贴)。因此,我们必须关闭这两个漏洞(WinForms代码):
System.Text.RegularExpressions;
...
private void MyTextBox_KeyPress(object sender, KeyPressEventArgs e) {
// we don't accept whitespace characters
if (char.IsWhiteSpace(e.KeyChar))
e.Handled = true;
}
private void MyTextBox_TextChanged(object sender, EventArgs e) {
// We remove whitespaces from text inserted
(sender as TextBox).Text = Regex.Replace((sender as TextBox).Text, @"\s+", "");
}
Run Code Online (Sandbox Code Playgroud)
如果您不想使用正则表达式,请尝试使用Linq:
(sender as TextBox).Text = string.Concat((sender as TextBox)
.Text
.Where(c => !char.IsWhiteSpace(c)));
Run Code Online (Sandbox Code Playgroud)