首页 > 解决方案 > 在文本框中只输入字母,也只用一个减号 (-) 最好使用 ASCII 码

问题描述

我想使用减号ASCII 码。有没有可能的方法呢?只使用一次减号。 45是减号 (-) 的 ASCII 码

private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);// e.KeyChar == (char)Keys.45);
}

标签: c#winformsascii

解决方案


要只允许使用连字符/减号一次,您需要检查 TextBox 是否已经包含一个。如果是,则设置e.Handled为 true。您的其余逻辑应该可以正常工作。

你可以使用这样的东西:

private void txtcity_KeyPress(object sender, KeyPressEventArgs e)
{
    // If you want to use the ASCII code, for some reason.
    const int minusAsciiCode = 45;

    // if (e.KeyChar == '-')
    if (e.KeyChar == (char)minusAsciiCode)
    {
        e.Handled = txtcity.Text.Contains("-");
    }
    else
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
    }
}

推荐阅读