【问题标题】:Keypress Event: Return another key按键事件:返回另一个键
【发布时间】:2015-03-18 15:06:51
【问题描述】:

我正在尝试构建一个仅允许使用数字和逗号的文本框,以使其内容填充访问“数字”列。我使用了 keypress 事件,使用以下代码使其接受数字和点,现在我想设置此代码以在按下点键(来自数字键盘和键盘)时写一个逗号

private void "Mytextbox_KeyPress"(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;
        if (!Char.IsDigit(ch) && ch != 8 /*backspace*/ && ch != 46 /*canc*/ && ch != 13 /* 13=enter*/ )
        {
            e.Handled = true;
      // if ch == 110 (dot) need to return 188 (comma)
    }

【问题讨论】:

  • 现在不能真正测试这个,但可能做e.KeyChar = ',';应该就足够了。根据msdnGets or sets the character corresponding to the key pressed.
  • 非常感谢,补充:else if (ch == '.') { e.KeyChar = ','; } 完美运行!

标签: c# textbox keypress


【解决方案1】:

这就是你所需要的:

private void Mytextbox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 46)
        e.KeyChar = (char)44;
}

它将用逗号替换点。不要使用e.Handled,因为这会抑制密钥而不是替换它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2020-06-26
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多