Skip to main content
 首页 » 编程设计

c#之防止在 C# TextBox 中打印空格

2024年02月05日10softidea

我想制作一个不允许输入空格的文本框。我禁用了键盘输入空格:

void textBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == (char)Keys.Space) 
    { 
        e.Handled = true; 
    }  
} 

但是如果用户复制了一个像“Hello world”这样带有空格的字符串,他可以把它粘贴到TextBox中,里面就会有空格。

请您参考如下方法:

您可以为您的 TextBox 添加一个 TextChanged 事件处理程序,并在该 TextChanged 事件中添加以下代码:

TextBox1.Text = TextBox1.Text.Replace(" ", "");