如何阻止用户在c#文本框中输入空格

本文关键字:输入 空格 文本 何阻止 用户 | 更新日期: 2023-09-27 18:13:12

我想限制用户在文本框中输入空格,在我的代码中,它只是获得第一个输入,然后检查它是否为空格。我想做的是在整个文本中用户不能在文本框

中输入空格
    private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((sender as TextBox).SelectionStart == 0)
            e.Handled = (e.KeyChar == (char)Keys.Space);
        else
            e.Handled = false;
    }

如何阻止用户在c#文本框中输入空格

你需要使用textbox changed event来防止复制粘贴空白

    private void txtPassword_TextChanged(object sender, EventArgs e)
    {
        if (txtPassword.Text.Contains(" "))
        {
            txtPassword.Text = txtPassword.Text.Replace(" ", "");
            txtPassword.SelectionStart = txtPassword.Text.Length;
        }
    }